作为Powershell脚本的一部分,我需要执行一个通常是快速的任务,但有时需要花费很长的时间。我想要执行这个任务,然后等待它完成,或者等待设定的时间过去,不管先发生什么。当任何一种情况发生时,我需要Powershell脚本返回到命令提示符。
下面是我想出的最接近的(以ping为例)
$x = Start-Process -Filepath "ping" -ArgumentList 'google.com -n 100' -NoNewWindow -PassThru;
Start-Sleep -Seconds 5;
try { Stop-Process -Id $x.Id -ErrorAction stop } catch {};这将在到达timoeout (如果仍在运行)之后终止进程,并返回到提示符。但是,如果命令在超时之前成功完成,则不会返回到提示符。这将导致脚本总是花费时间,不管超时值中指定了多长时间。
所需的语义与Linux的超时命令相似或相同。
要求:
发布于 2020-01-14 17:36:11
编辑使用ping代替记事本。我把等待过程和“$”结合起来?变成一个带有"$( )“的语句,因为powershell "if”查看的是输出,而不是退出状态。
start ping 'google.com -n 100'
if (-not $(wait-process ping 10; $?)) {
stop-process -name ping }发布于 2020-01-14 16:49:06
我认为一些要求可以通过使用秒表来满足,您必须测试SSH连接。
$timeOut = New-TimeSpan -Seconds 5
$stopWatch = [System.Diagnostics.Stopwatch]::StartNew()
do {
try {
Test-Connection -ComputerName google.ca -Count 1 -ErrorAction Stop
$timeOut = New-TimeSpan -Seconds 0 #Stop the stopWatch, we got a response
}
catch { #Write-Host "No response" }
}
While ($stopWatch.elaspsed -lt $timeOut)https://stackoverflow.com/questions/59737665
复制相似问题