1

I want to create a loop in my Powershell script that will run for a specific number of seconds, is that possible?

Here's what I have so far, not sure if it's right. I was hoping for a more straightforward way to do this. is it possible?

function collectProcess {
    param (
        #processnamn
        $process,
        #limit for the WS
        $limit,
        #Amount of seconds the loop will run
        $length
    )
    #Creating a new time span with the amount of seconds given
    $timeout = new-timespan -Seconds $length
    #starting a timer to compare later with the timeout
    $timer = [diagnostics.stopwatch]::StartNew()
    while ($timer.elapsed -lt $timeout) {
        $tempProcess= Get-Process -Name $process
        if ($tempProcess.WS -gt $limit) {
            Stop-Process -Name $process -Force
            Write-Host ("Process has stopped now"+ " The WS is: "+ $tempProcess.WS + " and our limit is: "+$limit )
            break;
        }

    }

}

Powershell version: 5.1

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
random-xyz
  • 137
  • 4
  • 14
  • Does this answer your question? [Powershell/PowerCLI Loop, timeouts and exits](https://stackoverflow.com/questions/42640113/powershell-powercli-loop-timeouts-and-exits) – iRon May 17 '20 at 16:38
  • That's not bad. I would put a `sleep 1` in the loop to cut down some cpu. – js2010 May 17 '20 at 18:23

1 Answers1

1

Instead of a TimeSpan (which denotes the length of a duration of time), you'll want to create a DateTime object that describes a point in time exactly X seconds from now:

$XSecondsFromNow = (Get-Date).AddSeconds($length)

while((Get-Date) -lt $XSecondsFromNow){
  # ...
}

You might want to ensure the user doesn't provide a negative (or ridiculously large) value, for that I'd suggest applying the ValidateRange parameter attribute:

param(
  [string]$ProcessName,

  [long]$Limit,

  [ValidateRange(0.5, 3600.0)]
  [double]$TimeOut
)

$XSecondsFromNow = (Get-Date).AddSeconds($TimeOut)

while((Get-Date) -lt $XSecondsFromNow){
  # ...
}
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206