Is it possible to get the exit code of a process I didn’t start?

0
7
Asked By CuriousCat87 On

I'm curious if I can retrieve the exit code for a process that I didn't initiate through my PowerShell script. I know I can use Get-Process to get a handle on the running process, but once it stops, I'm not sure how to access the exit code. The ExitCode property seems like it could help, but I'm unsure how to utilize it after the process has ended. Can someone guide me on this? Here's a little script I'm experimenting with:

```powershell
$ProcessName = 'Notepad'

:MainLoop While ($True) {
If (Get-Process $ProcessName -ErrorAction SilentlyContinue) {
While ($True) {
Write-Host "[$ProcessName] is running..."
If (-not(Get-Process $ProcessName -ErrorAction SilentlyContinue)) {
Write-Host "[$ProcessName] has stopped."
Break MainLoop
}
Start-Sleep -Seconds 5
}
} Else {
Write-Host "[$ProcessName] is not running."
Start-Sleep -Seconds 5
}
}
```

2 Answers

Answered By PowerShellWhiz On

You don’t need that entire loop you’ve set up. Instead, just get the process and use the `WaitForExit()` method. This will keep a hold of the process object, so you can retrieve the exit code after it finishes. Here's a simplified version of your script:

```powershell
$Process = Get-Process $ProcessName
$Process.WaitForExit()
$Process.ExitCode
```
Also, you'll want to run PowerShell as an admin if the process you’re trying to access was started with elevated privileges; otherwise, you won't see its exit code.

InquisitiveDev -

Thanks for the advice! But would using `WaitForExit()` potentially cause my script to hang indefinitely? Should I consider running that as a job instead so I can set a timeout?

Answered By TechGuru99 On

You can actually store the process handle and access its exit code even after the process has terminated. For example, you can do something like this:

```powershell
$a = ps -id
$handle = $a.handle
$a.ExitCode
```
This approach allows you to keep a reference to the process object so that you can retrieve the exit code later, even after it has closed. Just make sure to monitor processes properly, as demonstrated in this living example with an uninstaller. It shows how to wait for the process to complete and then get the exit code. Just be aware of how handles work in the background.

Also, don't forget to use `exit $proc.exitcode` after invoking the process!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.