我运行了一个执行许多WMI-查询的脚本,但是如果服务器没有响应,则cmdlet挂起。如果X秒过去了,我有什么办法让这个(或其他的cmndlet )超时并退出吗?
编辑
由于mjolinor的提示,解决方案是以-asjob的形式运行它,并在while循环中设置一个超时。但这是从作业内部运行的(从Start-作业开始)。那么我怎么知道我在控制正确的工作呢?
这是我已经开始工作的代码:
Get-WmiObject Win32_Service -ComputerName $server -AsJob
$Complete = Get-date
While (Get-Job -State Running){
If ($(New-TimeSpan $Complete $(Get-Date)).totalseconds -ge 5) {
echo "five seconds has passed, removing"
Get-Job | Remove-Job -Force
}
echo "still running"
Start-Sleep -Seconds 3
}PS:我的工作从一开始就开始了--工作已经被处理好了。
发布于 2012-03-14 21:45:40
对于这个问题,我看到的唯一两种解决方案是:
发布于 2012-12-21 21:44:47
您可以尝试get-wmiCustom函数,发布了这里。如果有一个超时参数,那不是很好吗?让我们投票给这玩意儿。
发布于 2014-10-15 17:32:06
我已经修改了Daniel的Get-WmiCustom,以支持传递凭据。
我知道这篇文章有点老了,希望这能帮到别人。
# Define modified custom get-wmiobject for timeout with credential from http://blogs.msdn.com/b/dmuscett/archive/2009/05/27/get_2d00_wmicustom.aspx
Function Get-WmiCustom([string]$Class,[string]$ComputerName,[string]$Namespace = "root\cimv2",[int]$Timeout=15, [pscredential]$Credential)
{
$ConnectionOptions = new-object System.Management.ConnectionOptions
$EnumerationOptions = new-object System.Management.EnumerationOptions
if($Credential){
$ConnectionOptions.Username = $Credential.UserName;
$ConnectionOptions.SecurePassword = $Credential.Password;
}
$timeoutseconds = new-timespan -seconds $timeout
$EnumerationOptions.set_timeout($timeoutseconds)
$assembledpath = "\\$Computername\$Namespace"
#write-host $assembledpath -foregroundcolor yellow
$Scope = new-object System.Management.ManagementScope $assembledpath, $ConnectionOptions
$Scope.Connect()
$querystring = "SELECT * FROM " + $class
#write-host $querystring
$query = new-object System.Management.ObjectQuery $querystring
$searcher = new-object System.Management.ManagementObjectSearcher
$searcher.set_options($EnumerationOptions)
$searcher.Query = $querystring
$searcher.Scope = $Scope
trap { $_ } $result = $searcher.get()
return $result
}https://stackoverflow.com/questions/9710512
复制相似问题