How to wait for a remote process in PowerShell

A short one today. I’ve been scripting in PowerShell (v1) recently, and had enormous trouble working on remote PCs (the full remoting functionality has not been enabled in our environment yet, so things like Enter-PSSession don’t work). One thing that cost me more nerve cells than usual was the synchronization of remote processes, since PS doesn’t really offer any means for that by default. I was, however, able to find a workaround.

Essentially, what you need is the cmdlet Get-Process. Normally, it returns the object representing a process identified by the PID you pass to it, but thanks to its ability to check for processes on remote computers and the fact that it sets the return code to True if a process corresponding to the PID is found and to False otherwise, it can be abused for our purpose. In fact, following code should do the trick:

do {
	Get-Process -id $PID -computername $remoteComputerName
} while ($?)

Where “$PID” contains the numeric ID of the process on the remote computer and “$?” is the boolean PS command return code. The do-while loop checks the return value of Get-Process inside it and exits once it turns to False (meaning that the remote process can no longer be found, i.e. it terminated).

However, you will soon notice that the Get-Process throws exceptions and prints totally unnecessary output once the process is not found. To avoid that, you need to suppress the exceptions and reroute the output into Out-Null by adding following to the cmdlet call:

-ea SilentlyContinue | Out-Null

Full code in a single line:

do { Get-Process -id $PID -computername $remoteComputerName -ea SilentlyContinue | Out-Null } while ($?)

Alternatively, you can just wrap the whole thing in a subroutine. Enjoy.

This entry was posted in powershell. Bookmark the permalink.