gpt4 book ai didi

powershell - 运行作业时的参数解释

转载 作者:行者123 更新时间:2023-12-01 20:23:25 26 4
gpt4 key购买 nike

$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 orempty. Supply an argument that is not null or empty and then try the commandagain.    + CategoryInfo          : InvalidData: (:) [Get-WmiObject], ParameterBindingValidationException    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.GetWmiObjectCommand    + PSComputerName        : localhost

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

最佳答案

除非使用 using 限定符,否则在脚本全局范围内定义的变量在脚本 block 内不可用:

$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

关于powershell - 运行作业时的参数解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37986872/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com