How to Get Exit Code of a Non-Started Process?

0
0
Asked By TechWiz88 On

I'm trying to find out if there's a way to get the exit code of a process that my script didn't start. If I use Get-Process to get a handle on it and wait for that process to finish, can I find out its exit code after it's done? I noticed that when a process stops, the exit code seems to be inaccessible. For context, I've been playing around with a script that checks if Notepad is still running, but I'm not sure how to retrieve the exit code once it closes. Here's a simplified version of my script:

```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 PowerShellNinja On

You don't need that complex loop. Once the process has exited, the process object is kept around by the Windows kernel until all handles are used. Just keep one reference and use `$Process.WaitForExit()` to wait for it to finish. Here's how your script should look:

```powershell
$Process = Get-Process $ProcessName
$Process.WaitForExit()
$Process.ExitCode
```
Make sure you're running PowerShell with elevated privileges to access exit codes for processes that have higher permissions.

CuriousCoder11 -

Got it, but would using .WaitForExit() mean I could potentially be waiting indefinitely? Maybe it’s a good idea to run that as a job so I can control the timeout?

Answered By ScriptGuru42 On

You actually can get the exit code even after the process has ended, but you need to store the process handle first. Check this snippet:

```powershell
$a = Get-Process -Id 14004
$handle = $a.Handle
$a.ExitCode
```
This way, you can retrieve the exit code as long as you hold the process object before it gets cleaned up by the system. In practice, with a process that might be running an uninstall command or something similar, waiting for it and then checking using the stored handle can work well!

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.