2

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?

shalomb
  • 3,456
  • 2
  • 23
  • 19

1 Answers1

4

Looking at it from the perspective of a single scriptblock:

$sb = { hostname.exe }
$result = @{}
$result.out = & $sb
$result.status = $?
$result.exitcode = $LASTEXITCODE

If you then dump $results out to examine the properties:

PS C:\> $results

Name                           Value
----                           -----
exitcode                       0
out                            POSHVM7
status                         True

Looping over the scriptblocks in $tasks you could just have an array of results that you would append to:

$results = @()
$Tasks | % {
  $result = @{}
  $result.out = & $_
  $result.status = $?
  $result.exitcode = $LASTEXITCODE
  $results += $result
}
Goyuix
  • 23,614
  • 14
  • 84
  • 128
  • I think while what you've showed me works - in actuality, I have something very similar to this answer http://stackoverflow.com/a/8635765/742600 and I'm passing a scriptblock in to invoke - but that's where I am unable to gather the $LASTEXITCODE. I think I'll ask a new question. – shalomb Nov 29 '13 at 16:50