Public/Wait-PrismTask.ps1

function Wait-PrismTask {
    <#
    .SYNOPSIS
        Waits for a Prism Central task to finish.
 
    .DESCRIPTION
        Polls Get-PrismTask until the task status is SUCCEEDED, FAILED or CANCELED.
        Returns the final task object provided by Get-PrismTask,
        including when the task fails or is canceled. Request errors stop polling.
 
    .PARAMETER PrismSession
        The server/FQDN of the PrismSession to use. May be omitted when only one session exists.
 
    .PARAMETER ExtId
        The external identifier of the task to wait for. Pass the .extId
        value returned by an asynchronous operation directly.
 
    .PARAMETER Task
        A PrismTask to wait for, either explicitly or from the pipeline. Uses its
        ExtId and originating PrismSession unless -PrismSession is specified.
 
    .PARAMETER PollIntervalSeconds
        Seconds between status requests. Defaults to 5. The first request is immediate.
 
    .PARAMETER TimeoutSeconds
        Maximum seconds to poll each task before throwing a timeout error. When omitted,
        polling has no time limit. Does not interrupt an in-progress status request.
 
    .PARAMETER DisplayUpdates
        Writes the task identifier and status on each poll to the information
        stream using Write-Host.
 
    .EXAMPLE
        $task = Start-PrismVM -ExtId $vmId
        Wait-PrismTask -Task $task -DisplayUpdates
 
    .EXAMPLE
        Wait-PrismTask -ExtId $taskId -PrismSession 'pc.lab.local' -PollIntervalSeconds 10
 
    .OUTPUTS
        The final PrismTask, including failed or canceled tasks.
    #>


    [CmdletBinding(DefaultParameterSetName = 'ByTask')]
    [OutputType([PrismTask])]
    param(
        [Parameter(Mandatory = $false,
            HelpMessage = 'Prism Session Name')][string]$PrismSession,

        [Parameter(Mandatory = $true,
            ParameterSetName = 'ById',
            ValueFromPipeline = $true,
            ValueFromPipelineByPropertyName = $true,
            HelpMessage = 'Task external identifier')]
        [Alias('Id', 'TaskExtId')][ValidateNotNullOrEmpty()][string]$ExtId,

        [Parameter(Mandatory = $true, ParameterSetName = 'ByTask', ValueFromPipeline = $true)]
        [ValidateNotNull()][PrismTask]$Task,

        [Parameter(Mandatory = $false)]
        [ValidateRange(1, 2147483647)][int]$PollIntervalSeconds = 5,

        [Parameter(Mandatory = $false)]
        [ValidateRange(1, 2147483647)][int]$TimeoutSeconds,

        [Parameter(Mandatory = $false)][switch]$DisplayUpdates
    )

    process {
        $taskId = if ($PSCmdlet.ParameterSetName -eq 'ByTask') { $Task.ExtId } else { $ExtId }
        if ([string]::IsNullOrWhiteSpace($taskId)) { throw 'A task ExtId is required.' }
        $sessionName = if ($PSCmdlet.ParameterSetName -eq 'ByTask' -and -not $PSBoundParameters.ContainsKey('PrismSession')) {
            $Task.PrismSession
        } else { $PrismSession }
        $stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
        while ($true) {
            if ($TimeoutSeconds -gt 0 -and $stopwatch.Elapsed.TotalSeconds -ge $TimeoutSeconds) {
                throw [System.TimeoutException]::new("Task '$taskId' did not finish within $TimeoutSeconds seconds.")
            }

            $currentTask = Get-PrismTask -PrismSession $sessionName -ExtId $taskId -ErrorAction Stop
            if ([string]::IsNullOrWhiteSpace($currentTask.Status)) {
                throw "Task '$taskId' response did not contain a task status."
            }

            if ($DisplayUpdates.IsPresent) {
                Write-Host "Task '$taskId': $($currentTask.Status)"
            }

            if ($currentTask.Status -in @('SUCCEEDED', 'FAILED', 'CANCELED')) {
                return $currentTask
            }

            if ($TimeoutSeconds -gt 0) {
                $remainingMilliseconds = ($TimeoutSeconds * 1000.0) - $stopwatch.Elapsed.TotalMilliseconds
                if ($remainingMilliseconds -le 0) {
                    throw [System.TimeoutException]::new("Task '$taskId' did not finish within $TimeoutSeconds seconds.")
                }
                $sleepMilliseconds = [Math]::Min(2147483647, [Math]::Min($PollIntervalSeconds * 1000.0, $remainingMilliseconds))
                Start-Sleep -Milliseconds ([int][Math]::Ceiling($sleepMilliseconds))
            } else {
                Start-Sleep -Seconds $PollIntervalSeconds
            }
        }
    }
}