Thursday, 10 August 2017

Powershell Receive-Jobs Failing on scheduled tasks

Since get-wmiobject doesn't have a timeout parameter a favorite snippet of mine is to use something like this

$WMIjob = Get-WMIObject -class win32_operatingsystem -ComputerName $somecomputer -ErrorAction SilentlyContinue -AsJob | Wait-Job -Timeout 3
$win32OS = $WMIjob | Receive-Job -erroraction silentlycontinue
      do something...
This creates a 3 second timeout for WMI, which is very handy when querying hundreds of systems

This works fine in the ISE, but when using it in a scheduled task I get no result

There are lots of ways to output script errors. One way I like is to add a line to output the error object to a powershell xml file into my scheduled script.

$error | Export-Clixml C:\Scripts\errorcli.xml

Then load it into the ISE to have a look

$myerror = import-clixml  C:\Scripts\errorcli.xml

There is a 'jobstatefailed' error, what gives?

Invalid parameter
    + CategoryInfo          : InvalidResult: (:) [], ManagementException
    + FullyQualifiedErrorId : JobStateFailed

My google-fu doesn't reveal much information about this on the interwebs.
Turns out you need to run the scheduled task with highest privilages. Then it is happy