简体   繁体   中英

How can I start a process, pause for 2 hours and then kill a process in Powershell

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}

在单行脚本块中放置多个PowerShell命令时,必须用分号分隔命令:

if((Get-Process -Name test -ErrorAction SilentlyContinue) -eq $null){ ."C:\Program Files (x86)\test.exe" ; Start-Sleep -s 7200 ; Stop-Process -name test}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM