Wednesday, 2 October 2013

Howto gather stdout, $? and $LASTEXITCODE from a script block containing any code

Howto gather stdout, $? and $LASTEXITCODE from a script block containing
any code

I've a sequence of 'tasks' performed on a machine that are defined in
powershell scriptblocks like the following (they're infact passed in as a
more complex array of hashes that contain scriptblocks).
$Tasks = @(
{ hostname.exe },
{ Get-PowerShellFunction },
{ (GWMI Win32_OperatingSystem).Version -imatch '6.1' },
{ Get-PowerShellFunction },
{ cmd /c "smth && exit 45" }
)
These tasks are invoked with $Tasks[$i].Invoke() but have realized I can't
report on the status of a task as there appears to be no reliable way to
examine and use $? and/or $LASTEXITCODE after the .Invoke()
I'd like to be able to do these things.
Gather the output (stdout and stderr) from the invoked scriptblock code.
Get the status (e.g. $?) of the invoked scriptblock if the code within it
was powershell code as a Boolean ($True or $False).
Get the status (e.g. $LASTEXITCODE) of the invoked scriptnlock if the code
within it was an external command as an Int32 (0 for success, !0 for
failure).
Allow this for work for PowerShell >= 2.0.
Is this possible?

No comments:

Post a Comment