运行作业时的参数解释 [英] Parameter interpretation when running jobs
本文介绍了运行作业时的参数解释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
$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)
为什么上面的代码块会引发以下错误?
Why does the codeblock above raise the following error?
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 对象时的超时.但首先我需要通过作业执行获得结果.
I would like to use this to implement a timeout when getting WMI objects for multiple hosts in a loop. But first I need to get the results via job execution.
推荐答案
在脚本的全局范围内定义的变量在脚本块内不可用,除非您使用 using
限定符:
Variables defined in the global scope of your script are not available inside the scriptblock unless you use the using
qualifier:
$code = {
Get-WmiObject -Class "Win32_ComputerSystem" -Namespace "root\cimv2" -ComputerName $using:h
}
或将它们作为参数传递,如下所示:
or pass them in as arguments, like this:
$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
这篇关于运行作业时的参数解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文