如何在 PowerShell 中使用超时命令?

Timeout.exe 实际上是一个cmd 命令,它也可以在 PowerShell 中使用。让我们看看与 Timeout 命令相关的帮助。

timeout /?

如果我们看到超时参数列表,我们可以使用 /T 表示以秒为单位的时间和/NoBreak命令,它忽略指定时间的任何键。

示例

Write-Output "Timeout is for 10 seconds"
Timeout /T 10
Write-Output "This line will be executed after 10 seconds if not interuptted"
输出结果
PS C:\> C:\Temp\TestPS1.ps1
Timeout is for 10 seconds
Waiting for 5 seconds, press a key to continue ...

请注意:在上面的例子中,用户可以使用任意键来中断超时秒数来禁止用户中断使用/NoBreak开关。

示例

Write-Output "Timeout is for 10 seconds"
Timeout /NoBreak 10
Write-Output "This line will be executed after 10 seconds"
输出结果
PS C:\> C:\Temp\TestPS1.ps1
Timeout is for 10 seconds
Waiting for 2 seconds, press CTRL+C to quit ...

如果输入 Ctrl+C,它将终止整个脚本执行。