Get the window of a newly started process

May 3, 2012 at 3:33 PM

I was having trouble figuring out a good way to start a new process and then immediately grab its window. Start-Process -passThru is useful, but you can run into some issues if trying something like this:

$process = Start-Process -passThru notepad.exe
Select-Window $process

Why doesn't this work?

  • The process's window may not be immediately available so Select-Window doesn't return anything if it's called right after the Start-Process command.
  • The process ID of a started process doesn't always match the Window that was created
  • If you have multiple windows already open for that process, it's hard to select the right one.

To workaround this issue, I created a function called Select-WindowStarted which will start a process and then return the new window that was opened. I tested it for notepad, Firefox, and Chrome. I'm going to maintain this function in my PS profile at common.windowsetup.ps1. Here's the first version of the function so you can get the basic idea here:

function Select-WindowStarted($process, [string]$processName = "", $msTimeout = 1000){
    $startTime = get-date
    $endTime = $startTime.addMilliseconds($msTimeout)
    
    if ($processName -eq ""){
        $processName = $process
    }

    $currentWindows = Select-Window $processName

    $processID = Start-Process $process -passThru

    do {
        if((get-date) -gt $endTime){
            throw "Timeout while trying to Select window by process"
        }
    }
    while ((Select-Window $processName | where {!($currentWindows -contains $_)} | measure).count -eq 0)
    
    Select-Window $processName | where {!($currentWindows -contains $_)}
}

Coordinator
May 5, 2012 at 4:32 AM

Looks good - I can't think of any other way to make sure you got the newest window when there are multiples for the same process id.