Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Waiting for open windows to close

Status
Not open for further replies.

ComputersUnlimited

IS-IT--Management
Dec 18, 2013
37
0
6
US
I have written a powershell script that executes CCleaner to clean the system drive of garbage files. As you most likely know for third party apps like CCleaner to clean internet cache, history etc for web-browsers the browsers need to be closed. So the first line in the script is

Code:
(get-process | ? { $_.mainwindowtitle -ne "" -and $_.processname -ne "powershell" } )| stop-process

It works as expected and closes all active windows except for Powershell, however it doesn't close them fast enough before CCleaner starts. How can I pause the script until this line completes executing before continuing?

I have tried using wait-process as described in this link, however it is apparently won't work with the line above

I'd rather not use something to pause the script for X seconds, in case a user has a lot of open apps, one or more apps takes a while to close or it is just a slow system, I also don't want to pause the script any longer then necessary.

Anybody have any ideas or suggestions?
 
Instead of piping all the process to the stop command, you could put them into a variable and then loop through them to stop. Wait a bit and then check if they are stopped or still running.

Code:
$processes = get-process | ? { $_.mainwindowtitle -ne "" -and $_.processname -ne "powershell" }

#Generalized (I didn't test this, more of a concept)
$loop_count = 0
while ($processes -AND $loop_count -lt 5)  #<< Check to make sure $processes is valid otherwise use something like $processes.Count -gt 0 
{
foreach ($process in $processes)
{# stop process}
# wait like 2 seconds or some timeframe
# get processes, again, to confirm stoppage
$processes = get-process | ? { $_.mainwindowtitle -ne "" -and $_.processname -ne "powershell" }
$loop_count ++
}


Light travels faster than sound. That's why some people appear bright until you hear them speak.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top