Running Executables
Console Applications
PS> console_app.exe
PS> & console_app.exe
PS> Start-Process console_app.exe
GUI Applications
PS> gui_app.exe (1)
PS> & gui_app.exe (2)
PS> & gui_app.exe | Out-Null (3)
PS> Start-Process gui_app.exe (4)
PS> 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).
Console Streams
PS> $ErrorActionPreference = "Continue" (1)
PS> & console_app.exe *>&1 | % { $_ } (2)
PS> & console_app.exe *>&1 | ? { $_ -is [System.Management.Automation.ErrorRecord] } (3)
PS> & console_app.exe *>&1 | ? { $_ -is [System.Management.Automation.WarningRecord] } (4)
PS> & console_app.exe *>&1 | ? { $_ -is [System.Management.Automation.VerboseRecord] } (5)
PS> & console_app.exe *>&1 (6)
PS> & 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.
Exit Codes
PS> $LastExitCode
PS> $?
PS> $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.