如何在Powershell中使用Wait-Process?
PowerShell中的Wait-Process cmdlet用于等待进程停止,然后执行继续进行下一步。
示例
我们正在运行一个截图工具应用程序,我们需要先等待该过程停止,然后再进行下一步。
PS C:\> Get-Process SnippingTool | Select Name,Id,CPUName Id CPU
---- -- ---
SnippingTool 7440 2.0625
为了等待进程首先停止,我们将使用Wait-Process命令。您可以提供ProcessName或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.ps1Waiting for the Process to Stop
该过程一旦停止,
PS C:\> C:\Temp\TestPS1.ps1Waiting for the Process to Stop
Snipping tool Process is stopped
如果所需的进程无法停止,则执行将永远等待。您还可以提供以秒为单位的timeout参数,因此,如果进程无法在指定的时间内停止,则会抛出错误。
示例
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.ps1Waiting 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.ps1Waiting for the Process to Stop
CloseError: (System.Diagnostics.…cess (SnippingTool):Process) [Wait-Process],
TimeoutException
以上是 如何在Powershell中使用Wait-Process? 的全部内容, 来源链接: utcz.com/z/334542.html