How can you set a time limit for a PowerShell script to run for?

前端 未结 6 890
再見小時候
再見小時候 2021-01-05 15:36

I want to set a time limit on a PowerShell (v2) script so it forcibly exits after that time limit has expired.

I see in PHP they have commands like set_time_limit an

6条回答
  •  执念已碎
    2021-01-05 16:13

    I came up with this script.

    • Start-Transcript to log all actions and save them to a file.
    • Store the current process ID value in the variable $p then write it to screen.
    • Assign the current date to the $startTime variable.
    • Afterwards I assign it again and add the extra time to the current date to the var $expiration.
    • The updateTime function return what time there is left before the application closes. And writes it to console.
    • Start looping and kill process if the timer exceeds the expiration time.
    • That's it.

    Code:

    Start-Transcript C:\Transcriptlog-Cleanup.txt #write log to this location
    $p = Get-Process  -Id $pid | select -Expand id  # -Expand selcts the string from the object id out of the current proces.
    Write-Host $p
    
    $startTime = (Get-Date) # set start time
    $startTime
    $expiration = (Get-Date).AddSeconds(20) #program expires at this time
    # you could change the expiration time by changing (Get-Date).AddSeconds(20) to (Get-Date).AddMinutes(10)or to hours whatever you like
    
    #-----------------
    #Timer update function setup
    function UpdateTime
       {
        $LeftMinutes =   ($expiration) - (Get-Date) | Select -Expand minutes  # sets minutes left to left time
        $LeftSeconds =   ($expiration) - (Get-Date) | Select -Expand seconds  # sets seconds left to left time
    
    
        #Write time to console
        Write-Host "------------------------------------------------------------------" 
        Write-Host "Timer started at     :  "  $startTime
        Write-Host "Current time         :  "  (Get-Date)
        Write-Host "Timer ends at        :  "  $expiration
        Write-Host "Time on expire timer : "$LeftMinutes "Minutes" $LeftSeconds "Seconds"
        Write-Host "------------------------------------------------------------------" 
        }
    #-----------------
    
    
    do{   #start loop
        Write-Host "Working"#start doing other script stuff
        Start-Sleep -Milliseconds 5000  #add delay to reduce spam and processing power
        UpdateTime #call upadate function to print time
     }
    until ($p.HasExited -or (Get-Date) -gt $expiration) #check exit time
    
    Write-Host "done"
    Stop-Transcript
    if (-not $p.HasExited) { Stop-Process -ID $p -PassThru } # kill process after time expires
    

提交回复
热议问题