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
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.
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
or like this:
$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