如何暂停执行但保持脚本的其他部分运行



当前正在使用下面的,但希望在不暂停脚本的情况下将其更新为等待5分钟才能取消停机时间。

对此,最好的方法是什么?

Write-Host "Removing Downtime After Five Minutes..." -ForegroundColor Green
Start-Sleep -Seconds 300
Remove-Downtime -APIKey $APIKey -AppKey $AppKey -Scope "stack:$StackLower" | Out-Null

目前尚未测试任何功能。

您有几个选项。

一种是将脚本的其余部分作为作业运行

$Now = (get-date)
Start-Job {#Other stuff
# Rest of script goes here
# to continue running in parallel
} -Name 'Other things to run'
Write-Host "$($Now.ToString("HH:mm")) - Removing Downtime After Five Minutes..." -ForegroundColor Green
Start-Sleep -Seconds 300
Remove-Downtime -APIKey $APIKey -AppKey $AppKey -Scope "stack:$StackLower" | Out-Null
Get-Job | Wait-Job | Remove-Job

或者。。。

$Now = get-date
Write-Host "$($Now.ToString("HH:mm")) - Removing Downtime After Five Minutes..." -ForegroundColor Green
Start-Job {#Remove Downtime
Start-Sleep -Seconds 300
Remove-Downtime -APIKey $APIKey -AppKey $AppKey -Scope "stack:$StackLower" | Out-Null
} -Name 'Remove Downtime'
# Rest of script goes here
# to continue running in parallel
Get-Job | Wait-Job | Remove-Job

或者使用另一个PowerShell会话来显示消息。

$scriptblock = {
$Now = get-date
Write-Host "$($Now.ToString("HH:mm")) - Removing Downtime After Five Minutes..." -ForegroundColor Green
Start-Sleep -Seconds 300
Remove-Downtime -APIKey $APIKey -AppKey $AppKey -Scope "stack:$StackLower" | Out-Null
}
cmd /c start PowerShell -Command $scriptblock
# Rest of script goes here
# to continue running in parallel

你也可以选择高级选项,并使用Winforms来显示消息,以保持其清洁。

$scriptblock = {# Only a bare minimum of properties used
$Now = Get-Date
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$form = New-Object Windows.Forms.Form
$form.Text = "$($Now.ToString("HH:mm")) - Wait for me"
$form.MaximizeBox = $False
$form.MinimizeBox = $False
$form.ControlBox = $False
$label = New-Object System.Windows.Forms.Label
$label.Location = '10,10'
$label.Width = $form.Width - 20
$label.Text = 'Removing Downtime After Five Minutes...'
$form.Controls.Add($label)
$form.Show()
$form.WindowState = 'Normal'
$form.TopMost = $true
$form.Activate()
Start-Sleep -Seconds 300
$form.Dispose()
Remove-Downtime -APIKey $APIKey -AppKey $AppKey -Scope "stack:$StackLower" | Out-Null
}
cmd /c start /min PowerShell -Command $scriptblock
# Rest of script goes here
# to continue running in parallel

最新更新