Do…until Process Killed — Powershell
I really enjoy using powershell to automate processes. One thing I repeatedly find myself doing is wanting to run (or not run) a specific piece of code until a program or service has terminated. This little snippet is extremely simple, but does the job. If a given process is detected, it will continue to loop through the inner code until the “Until” section evaluates to true.
More often than not, I find myself checking to see if “msiexec” or another installer is running. If it is, continue, otherwise keep looping.
$ProcessList = @(
"notepad" #or whatever you want to monitor
)
Do {
$ProcessesFound = Get-Process | ? {$ProcessList -contains $_.Name} | Select-Object -ExpandProperty Name
If ($ProcessesFound) {
Write-Host "Still running: $($ProcessesFound)"
Start-Sleep 10
}
} Until (!$ProcessesFound)
The great part about this, is you can also add the -Computer
parameter to the Get-Process
command to run it on a remote system.
$ProcessList = @(
"notepad" #or whatever you want to monitor
)
Do {
$ProcessesFound = Get-Process -Computer $pcname | ? {$ProcessList -contains $_.Name} | Select-Object -ExpandProperty Name
If ($ProcessesFound) {
Write-Host "Still running: $($ProcessesFound)"
Start-Sleep 10
}
} Until (!$ProcessesFound)
An even easier way
If you don’t need to loop through any code during the waiting period, you can simply run this one-liner.
Get-Process -Name notepad,msiexec -ErrorAction SilentlyContinue | Wait-Process
Again, small and simple, but something I use all the time.