2
$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.

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.