Evaluating Exit Codes (aka Error Level – Part 3)

by Apr 26, 2017

In part 3 of our mini-series about running console applications in PowerShell, here is a goodie: how can you run a console application separately from PowerShell, and still get notified when it is done, and retrieve its exit code?

Here is how: the code below runs ping.exe in a separate (hidden) window. PowerShell continues and is free to do whatever it wants. In the example, it outputs a number of “dot” characters while ping.exe is busy pinging a hostname.

Once the exe is done, the code retrieves the process ExitCode information:

$hostname = 'powershellmagazine.com'
# run the console-based application ASYNCHRONOUSLY in its own 
# window (PowerShell continues) and return the 
# process object (-PassThru)
# Hide the new window (you can also show it if you want)
$process = Start-Process -FilePath ping -ArgumentList "$hostname -n 4 -w 2000" -WindowStyle Hidden -PassThru

# wait for the process to complete, and meanwhile
# display some dots to indicate progress:
    Write-Host '.' -NoNewline
    Start-Sleep -Milliseconds 300
} until ($process.HasExited)

# the Error Level information is then found in ExitCode:
$IsOnline = $process.ExitCode -eq 0

Twitter This Tip! ReTweet this Tip!