我在脚本下运行以从多个服务器获得CPU利用率。但是,我遇到了几台计算机,下面的脚本只是永远坚持下去,即没有错误,没有控制台输出。所以我在特定的时间段后使用了Job命令来杀死。但是当我试图执行这段代码时,我的错误就越来越差了。
有没有办法设置单个PowerShell命令的时间限制?
$ServerList = ("xyz","abc")
foreach ($computername in $ServerList) {
$timeout = 30
$job = Start-Job -ScriptBlock {
Get-WmiObject Win32_Processor -ComputerName $using:computername |
Measure-Object -Property LoadPercentage -Average |
Select Average
}
Wait-Job -Job $job -Timeout $timeout
Stop-Job -Job $job
Receive-Job $job
Remove-Job -Job $job
}
Cannot validate argument on parameter 'ComputerName'. The argument is null or empty. Supply an argument that is not null or empty and then try the command again. + CategoryInfo : InvalidData: (:) [Get-WmiObject], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.GetWmiObjectCommand
答案 0 :(得分:0)
抱歉,我错过了您使用的是PowerShell v2。在PowerShell v3之前,using:
范围修饰符不可用,因此您需要使用-ArgumentList
参数将计算机名称传递到scriptblock中。
改变这个:
$job = Start-Job -ScriptBlock {
Get-WmiObject Win32_Processor -ComputerName $using:computername |
Measure-Object -Property LoadPercentage -Average |
Select Average
}
进入这个:
$job = Start-Job -ScriptBlock {
Get-WmiObject Win32_Processor -ComputerName $args[0] |
Measure-Object -Property LoadPercentage -Average |
Select -Expand Average
} -ArgumentList $computername