如何在 PowerShell 中使用 Wait-Process?
PowerShell 中的Wait-Process cmdlet 用于在执行继续进行到下一步之前等待进程停止。
实例
我们运行了一个剪报工具应用程序,我们需要先等待进程停止,然后再执行下一步操作。
PS C:\> Get-Process SnippingTool | Select Name,Id,CPU Name Id CPU ---- -- --- SnippingTool 7440 2.0625
要先等待进程停止,我们将使用Wait-Process命令。您可以提供进程名称或 ID。
Write-Output "Waiting for the Process to Stop" Wait-Process -Name 'SnippingTool' Write-Output 'Snipping tool Process is stopped'
输出
PS C:\> C:\Temp\TestPS1.ps1 Waiting for the Process to Stop
进程停止后,
PS C:\> C:\Temp\TestPS1.ps1 Waiting for the Process to Stop Snipping tool Process is stopped
如果所需的进程不能停止,执行将永远等待。您还可以提供超时参数(以秒为单位),如果进程在指定时间内不能停止,则会抛出错误。
实例
Write-Output "Waiting for the Process to Stop" Wait-Process -Name 'SnippingTool' -Timeout 5 Write-Output 'Snipping tool Process is stopped'
输出
PS C:\> C:\Temp\TestPS1.ps1 Waiting for the Process to Stop CloseError: (System.Diagnostics.…cess (SnippingTool):Process) [Wait-Process], TimeoutException Snipping tool Process is stopped
在这种情况下,我们可以将**ErrorAction 设置更改为Stop。
实例
Write-Output "Waiting for the Process to Stop" Wait-Process -Name 'SnippingTool' -Timeout 5 -ErrorAction Stop Write-Output 'Snipping tool Process is stopped'
输出
PS C:\> C:\Temp\TestPS1.ps1 Waiting for the Process to Stop CloseError: (System.Diagnostics.…cess (SnippingTool):Process) [Wait-Process], TimeoutException
广告