I am writing an automation script. I had a function which takes either a command or an executable. I had to wait until the command or executable has completed running and return if failed or passed. I also want to write the output to file. I am trying with the Start-Job
cmdlet.
My current code:
$job = Start-Job -scriptblock {
Param($incmd)
$ret = Invoke-Expression $incmd -ErrorVariable e
if ($e) {
throw $e
} else {
return $ret
}
} -ArumentList $outcmd
Wait-Job $job.id
"write the output to file using receive-job and return if passed or failed"
This works perfectly fine for commands but for executables irrespective of errorcode the value of $e
is null. This falsely shows as passed even though the errorcode is 0.
I tried with errorcode using $LASTEXISTCODE
and $?
. But $?
is true for executables and $LASTEXISTCODE
is either null or garbage value for commands. I am out of ideas and struck here.