$h = "host1.example.com"
$code = {
$(Get-WmiObject -Class "Win32_ComputerSystem" -Namespace "root\cimv2" -ComputerName $h)
}
$timeout = 5
$jobstate = $(Wait-Job -Job ($job = $(Start-Job -ScriptBlock $code)) -Timeout $timeout)
$wmicomobj = $(Receive-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 + PSComputerName : localhost
我想在循环中为多个主机获取WMI对象时使用它来实现超时。但首先我需要通过执行作业来获得结果。
答案 0 :(得分:4)
除非您使用using
限定符,否则脚本块内的全局范围中定义的变量不可用:
$code = {
Get-WmiObject -Class "Win32_ComputerSystem" -Namespace "root\cimv2" -ComputerName $using:h
}
或将它们作为参数传递,如下所示:
$code = {
Param($hostname)
Get-WmiObject -Class "Win32_ComputerSystem" -Namespace "root\cimv2" -ComputerName $hostname
}
$jobstate = Wait-Job -Job ($job = $(Start-Job -ScriptBlock $code -ArgumentList $h)) -Timeout $timeout
或者像这样:
$code = {
Get-WmiObject -Class "Win32_ComputerSystem" -Namespace "root\cimv2" -ComputerName $args[0]
}
$jobstate = Wait-Job -Job ($job = $(Start-Job -ScriptBlock $code -ArgumentList $h)) -Timeout $timeout