PowerShell的测试路径超时
我正试图定期检查我们域上数百台计算机上文本文件中是否存在特定字符串PowerShell的测试路径超时,powershell,Powershell,我正试图定期检查我们域上数百台计算机上文本文件中是否存在特定字符串 foreach ($computer in $computers) { $hostname = $computer.DNSHostName if (Test-Connection $hostname -Count 2 -Quiet) { $FilePath = "\\" + $hostname + "c$\SomeDirectory\SomeFile.txt" if (Test-P
foreach ($computer in $computers) {
$hostname = $computer.DNSHostName
if (Test-Connection $hostname -Count 2 -Quiet) {
$FilePath = "\\" + $hostname + "c$\SomeDirectory\SomeFile.txt"
if (Test-Path -Path $FilePath) {
# Check for string
}
}
}
在大多数情况下,测试连接和测试路径的模式是有效和快速的。然而,有些计算机ping成功,但测试路径需要大约60秒才能解析为FALSE。我不知道为什么,但这可能是一个域信任问题
对于这种情况,我希望测试路径有一个超时,如果需要超过2秒,则默认为FALSE
不幸的是,相关线程中的解决方案不适用于我的情况。建议的do-while循环在代码块中挂起
我一直在尝试作业,但似乎即使这样也不会强制退出测试路径命令:
这项工作仍在幕后进行。这是我达到上述要求的最干净的方式吗?除了生成异步活动外,还有更好的方法使测试路径超时以使脚本不挂起吗?非常感谢。将您的代码包装在[powershell]对象中,并调用BeginInvoke以异步执行它,然后使用关联的WaitHandle仅在设定的时间内等待它完成
$sleepDuration = Get-Random 2,3
$ps = [powershell]::Create().AddScript("Start-Sleep -Seconds $sleepDuration; 'Done!'")
# execute it asynchronously
$handle = $ps.BeginInvoke()
# Wait 2500 milliseconds for it to finish
if(-not $handle.AsyncWaitHandle.WaitOne(2500)){
throw "timed out"
return
}
# WaitOne() returned $true, let's fetch the result
$result = $ps.EndInvoke($handle)
return $result
在上面的示例中,我们随机休眠2秒或3秒,但设置2.5秒的超时时间-尝试运行几次以查看效果:将代码包装在[powershell]对象中,并调用BeginInvoke以异步执行它,然后使用关联的WaitHandle等待它只完成一段设定的时间
$sleepDuration = Get-Random 2,3
$ps = [powershell]::Create().AddScript("Start-Sleep -Seconds $sleepDuration; 'Done!'")
# execute it asynchronously
$handle = $ps.BeginInvoke()
# Wait 2500 milliseconds for it to finish
if(-not $handle.AsyncWaitHandle.WaitOne(2500)){
throw "timed out"
return
}
# WaitOne() returned $true, let's fetch the result
$result = $ps.EndInvoke($handle)
return $result
在上面的示例中,我们随机睡眠2秒或3秒,但设置2.5秒的超时时间-尝试运行几次以查看效果:这是Windows文件共享问题,可能需要使用Windows注册表设置来减少超时时间,我不建议这样做。最好的解决方案是找出并解决超时/权限问题。一个相关的问题可能会提供一些帮助:另一个选项是并行运行foreach-parallel中的foreach块。在$hostname之后和C$之前是否缺少反斜杠?这是一个Windows文件共享问题,可能需要修改Windows注册表设置以减少超时,我不建议这样做。最好的解决方案是找出并解决超时/权限问题。一个相关的问题可能会提供一些帮助:另一个选项是并行运行foreach-parallel中的foreach块。在$hostname之后和C$之前是否缺少反斜杠?