【问题标题】:Parameter interpretation when running jobs运行作业时的参数解释
【发布时间】:2016-10-25 12:10:55
【问题描述】:
$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)

为什么上面的代码块会引发以下错误?

无法验证参数“计算机名”上的参数。参数为 null 或
空的。提供一个不为 null 或空的参数,然后尝试该命令
再次。
    + CategoryInfo : InvalidData: (:) [Get-WmiObject], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.GetWmiObjectCommand
    + PSComputerName : 本地主机

我想在循环中为多个主机获取 WMI 对象时使用它来实现超时。但首先我需要通过作业执行获得结果。

【问题讨论】:

    标签: powershell


    【解决方案1】:

    除非您使用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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-09
      • 1970-01-01
      • 2017-05-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多