≡ Menu

PowerShell: How to get exit code of a process

While working on a script that does file copy using Robocopy utility, I had the need to capture the exit code from the process I started. I relied on System.Diagnostics.Process dotnet class to start the copy operation using robocopy because it gives me an option to get the return code after the process completion.

So after my work, I started analyzing why such functionality can’t be achieved with Start-Process cmdlet. So, my conclusion is, it can be done with cmdlet as well. Let us see how to achieve that.

$process = Start-Process robocopy -ArgumentList "c:\scripts c:\temp\backup /MIR" -WindowStype Hidden -PassThru

By default start-process will not return process object it started. To get the process object, we need use the -PassThru parameter. The returned object has the capability to refresh its state automatically(I haven’t seen this with process objects returned by Get-Process). You can check HasExited value of the process obj attribute to determine it completed or not. It returns True when execution completed. And then ExitCode attribute will tell you the return code.

process-exit codeBelow are the some of the returns codes that robocopy exhibiting in different conditions.


Happy learning…

{ 0 comments… add one }

Leave a Comment