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 timestamped task status changes to the information stream using
        Write-Host. Repeated statuses are suppressed for each task being waited on.
 
    .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()
        $lastDisplayedStatus = $null
        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 -and $currentTask.Status -cne $lastDisplayedStatus) {
                Write-Host "[$([datetimeoffset]::Now.ToString('o'))] Task '$taskId': $($currentTask.Status)"
                $lastDisplayedStatus = $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.")
                }
                # Cap the conversion at Int32.MaxValue milliseconds (about 24.9 days),
                # not an infinite wait. Normally the poll interval or timeout is much shorter.
                $sleepMilliseconds = [Math]::Min([double][int]::MaxValue, [Math]::Min($PollIntervalSeconds * 1000.0, $remainingMilliseconds))
                Start-Sleep -Milliseconds ([int][Math]::Ceiling($sleepMilliseconds))
            } else {
                # Sleep in milliseconds so a large PollIntervalSeconds cannot overflow
                # Start-Sleep -Seconds (which caps near Int32.MaxValue / 1000 seconds).
                $sleepMilliseconds = [Math]::Min([double][int]::MaxValue, $PollIntervalSeconds * 1000.0)
                Start-Sleep -Milliseconds ([int][Math]::Ceiling($sleepMilliseconds))
            }
        }
    }
}