Skip to content

37. Running Executables

Note

The below information is extensively based in information taken from the PowerShell® Notes for Professionals book. I plan to extend this information based on my day to day usage of the language.

37.1: GUI Applications

1
2
3
4
5
gui_app.exe ( 1 )
& gui_app.exe ( 2 )
& gui_app.exe | Out-Null ( 3 )
Start-Process gui_app.exe ( 4 )
Start-Process gui_app.exe -Wait ( 5 )

GUI applications launch in a different process, and will immediately return control to the PowerShell host.

Sometimes you need the application to finish processing before the next PowerShell statement must be executed.

This can be achieved by piping the application output to $null (3) or by using Start-Process with the -Wait switch (5).

37.2: Console Streams

1
2
3
4
5
6
7
$ErrorActionPreference = "Continue" ( 1 )
& console_app.exe *>& 1 | % { $_ } ( 2 )
& console_app.exe *>& 1 |? { $_ -is [System.Management.Automation.ErrorRecord] } ( 3 )
& console_app.exe *>& 1 |? { $_ -is [System.Management.Automation.WarningRecord] } ( 4 )
& console_app.exe *>& 1 |? { $_ -is [System.Management.Automation.VerboseRecord] } ( 5 )
& console_app.exe *>& 1 ( 6 )
& console_app.exe 2 >& 1 ( 7 )

Stream 2 contains System.Management.Automation.ErrorRecord objects. Note that some applications like git.exe

use the "error stream" for informational purposes, that are not necessarily errors at all. In this case it is best to look at the exit code to determine whether the error stream should be interpreted as errors. PowerShell understands these streams: Output, Error, Warning, Verbose, Debug, Progress. Native applications commonly use only these streams: Output, Error, Warning.

In PowerShell 5, all streams can be redirected to the standard output/success stream (6).

In earlier PowerShell versions, only specific streams can be redirected to the standard output/success stream (7). In this example, the "error stream" will be redirected to the output stream.

37.3: Exit Codes

1
2
3
$LastExitCode
$?
$Error[ 0 ]

These are built-in PowerShell variables that provide additional information about the most recent error.

$LastExitCode is the final exit code of the last native application that was executed. $? and $Error[^0 ] is the last error record that was generated by PowerShell.