Reputation: 35
How can I start a process, pause for 2 hours and then kill a process in Powershell. I can get it to launch the process and kill the process but the Start-Sleep command doesn't seem to be working in my script. I thought this would be simple. Not sure if I'm missing something or if this is even possible to sleep for 2 hours.
if((Get-Process -Name test -ErrorAction SilentlyContinue) -eq $null){
."C:\Program Files (x86)\test.exe" Start-Sleep -s 7200 Stop-Process -name test}
Upvotes: 3
Views: 6778
Reputation: 3336
just to add something to Jeff's answer - you can use Start-Process
and -PassThru
to make sure you're ending the correct process that you launched.
if ((Get-Process 'test' -EA SilentlyContinue) -eq $null){
$Process = Start-Process "C:\Program Files (x86)\test.exe" -PassThru
Start-Sleep -Seconds (2*60*60)
$Process | Stop-Process
}
this will mean that if the process dies for another reason and is relaunched manually or by another copy of the script etc, that this script won't just kill it after two hours, but will kill the correct process.
Upvotes: 5
Reputation: 10809
When you are placing multiple PowerShell commands in a single-line script block, you must separate the commands with semicolons:
if((Get-Process -Name test -ErrorAction SilentlyContinue) -eq $null){ ."C:\Program Files (x86)\test.exe" ; Start-Sleep -s 7200 ; Stop-Process -name test}
Upvotes: 4