Windows PowerShell Script termination

~OSD~ 2,201 Reputation points
2024-03-04T12:28:02.4066667+00:00

Hi,

Copying files /folders with PowerShell script.
Copy-Item -Force -Recurse -Path Source -Destination
It works fine (usually) but sometimes "stuck" in the execution and never ends. Is there a way to define the maximum execution time, for example, 5 minutes, if it has been 5 minutes or more, terminate the script execution and reboot the machine.

I understand that source and target files will not be the same with the cancellation during the execution, but currently, it's acceptable to have a few files copied compared to a never-ending process.

Windows for business Windows Server User experience PowerShell
Windows for business Windows Client for IT Pros User experience Other
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Rich Matheisen 47,901 Reputation points
    2024-03-04T15:36:21.88+00:00

    Start a separate PowerShell process (Start-Process using the -Passthru switch) and save the value in a variable. Then use Start-Sleep -Seconds (5*60). When the launching script awakes, check the status of the process that you started. If it's still running, stop it.

    If the 2nd script finishes before 5 minutes you'll still wait 5 minutes, though.

    Alternatively, you can create a loop in the launching script that repeatedly waits a few seconds, checks to see if the 2nd script is still running and either exits the loop if the 2nd script is finished or stops the process if the elapsed time is greater than 5 minutes.


  2. Rich Matheisen 47,901 Reputation points
    2024-03-05T03:26:21.0833333+00:00

    Probably the easiest way is to use a background job:

    $j = Start-Job -ScriptBlock{Start-Sleep 15}
    $b = $j.PSBeginTime
    $s = $b.AddMinutes(0.1)							# stop job after this long
    
    while ($true){
        Write-Host "Sleeping"                       # not for production, just for demo
        Start-Sleep -Seconds 10
        $j|Get-Job                                  # not for production, just for demo
        if ($j.State -eq 'Completed'){
            Write-Host "Job completed"              # not for production, just for demo
            break
        }
        if ( (Get-Date) -gt $s){
            Write-Host "Time's up. Stopping job"    # not for production, just for demo
            $j|Stop-Job
            break
        }
    }
    $j|receive-job
    $j|remove-job
    
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.