Wait-IpsJob.ps1
<# .Synopsis Implement an common task to wait for job completion. .Description Implement an common task to wait for job completion. This function supports a follow-up iteration of getting job status for both export and prepare. #> Function Wait-IpsJob { [CmdletBinding()] Param( [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)] [string]$CustomerId, [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] [string]$Deployment, [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)] [string]$JobId, [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] [string]$SecureClientId = '', [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] [string]$SecureSecret = '', [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] [string]$LogFileDir = "", [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] [string]$LogFileName = 'WaitJob.log', [Parameter(Mandatory = $false)] [int]$PollSeconds = 60, [Parameter(Mandatory = $false)] [switch]$OverwriteLog ) Begin { Add-PSSnapin Citrix.* } Process { # Initialize Logger LogInit $LogFileDir $LogFileName $OverwriteLog $False if ($JobId -eq "Job failed to start") { return } if ([string]::IsNullOrWhiteSpace($JobId)) { throw "Must supply a job id" } # Start waiting for job $job = $null $terminated = $false while (-Not $terminated) { # Send the GET try { $job = Invoke-CCRestMethod 'Get' $Deployment "jobs\$JobId" $CustomerId $SecureClientId $SecureSecret @{} $null LogIt "Job $JobId status: $($job.status) percent done: $($job.overallProgressPercent) parameters $($job.parameters)" } catch { LogIt "GET jobs\$JobId status error: $($_)" return New-Object PSObject -Property @{ status = "Failed" error = $_ additionalInfo = @{ artifacts = @{} } } } if ('notStarted','inProgress' -contains $job.status) { Start-Sleep $PollSeconds } else { $terminated = $true } } if ($job.status -eq "complete") { LogIt "Job $JobId final status: $($job.status)" LogIt "Completed job $(Convert-HashToString (Convert-ObjectToHashtable $job)) " $false } else { LogIt "Job $JobId final status: $(Convert-HashToString (Convert-ObjectToHashtable $job)) " throw "Final job $JobId status: $($job.status)" } #Check if it comes to the end of pipeline if ($PSCmdlet.MyInvocation.PipelinePosition -lt $PSCmdlet.MyInvocation.PipelineLength) { LogIt "Current pipeline position $($PSCmdlet.MyInvocation.PipelinePosition)/$($PSCmdlet.MyInvocation.PipelineLength)" $false $output = [PSCustomObject]@{ artifacts = $job.additionalInfo.artifacts } Write-Output $output } else { LogIt "Pipeline finished" $false Clear-XDCredentials } return @{ status = $job.status artifacts = $job.additionalInfo.artifacts } } } |