PowerShell: Stop command at certain date/time

Sometimes it can be handy to automatically stop a process at a certain time.
I did this using the following powershell script. The script will first ask at what time it needs to be stopped. You can specify seconds if needed, but not required, or you can specify a date. Even milliseconds, but keep in mind that it will only run with 100 milliseconds precision. It will stop the process mentioned in the script. The title of the powershell window will be set, in order to easily see that this Powershell window is executing this script.

$host.ui.RawUI.WindowTitle = "Stop Process at certain time" $Process="notepad" Clear-Host #resize, just for fun $pshost = Get-Host             $pswindow = $pshost.UI.RawUI     $newsize = $pswindow.windowsize  $newsize.width = 80 $newsize.height = 20 $pswindow.windowsize = $newsize ### check if process is running before start $Running = Get-Process -Name $Process -ErrorAction SilentlyContinue if($Running -eq $null) # evaluating if the program is running { Write-Host "$Process not active." exit 1 }  $Tijd= Read-Host -Prompt 'At which time to stop: ' $host.ui.RawUI.WindowTitle = "Stop Process at $Tijd" Write-Host "We will wait till '$Tijd'  in order to stop the $Process process" Write-Host "Waiting..." do { Start-Sleep -m 100 } until ((get-date) -ge (get-date $Tijd)) Write-Host "It is $Tijd. Process will be stopped." ### check if process is running before killing. Just to notify user that nothing was killed $Running = Get-Process -Name $Process -ErrorAction SilentlyContinue if($Running -eq $null) # evaluating if the program is running { Write-Host "$Process not active anymore." exit 1 }  Stop-Process -name $Process -ErrorAction SilentlyContinue Write-Host "$Process was stopped at $(Get-Date)"
Share your love