Reputation: 40553
When I use start-process
to create a new process and assign it to a variable...
$np = start-process -passThru notepad
... and then query .MainWindowHandle
...
$np.MainWindowHandle
... I seem to be given the HWND of the notepad.
However, when I try to do the same thing in one go...
(start-process -passThru notepad).MainWindowHandle
... I am given 0
.
This is probably the case because MainWindowHandle
is evaluated before notepad has created its window.
So, is there a way, without using start-sleep
or going into a loop that repeadetly queries the value of MainWindowHandle
, to wait until notepad is done starting up?
Upvotes: 0
Views: 256
Reputation: 174760
So, is there a way,
without using
start-sleep
or going into a loop that repeadetly queries the value ofMainWindowHandle
# Define a timeout threshold 10 seconds into the future
$threshold = (Get-Date).AddSeconds(10)
# Start the process
$proc = Start-Process notepad -PassThru
while(-not $proc.HasExited -and ((Get-Date) -lt $threshold -or $proc.MainWindowTitle -eq 0)){
Start-Sleep -MilliSeconds 250
}
if($proc.MainWindowTitle -eq 0){
if(-not $proc.HasExited)
$proc.Terminate()
}
throw 'Failed to spawn window in time'
return
}
# Do stuff with $proc.MainWindowHandle
Upvotes: 1