snakePlantLeaf
snakePlantLeaf

Reputation: 73

Terminate part of powershell script and continue

I made a powershell script, that reads remote PCs registry keys, and prints them out to an html page.

Sometimes remote PCs freeze/hang, etc. This increases the final html page by around 40 sec for each frozen PC.

How can I time just a part of my script, let's say 1-2 commands and if that time gets too large, i terminate that command and continue script with the next PC out of PC name-array? Or maybe the solution is not in timing, is there other way? Thanks!

Smth like:

$Reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('Users', $remote[$i]) + timer runs in parallel + if condition for the timer count. And when the counter reaches threshold terminate OpenRemoteBaseKey & continue

Upvotes: 1

Views: 376

Answers (1)

Adam
Adam

Reputation: 4168

Execute the statement as a job. Monitor the time outside the job. If the job runs longer than you prefer, kill it.

$job = Invoke-Command `
  -Session $s
  -ScriptBlock { $Reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('Users', $remote[$i]) } `
  -AsJob `
  -JobName foo

$int = 0

while (($job.State -like "Running") -and ($int -lt 3)) {
  Start-Sleep -Seconds 1
  $int++
}

if ($Job.State -like "Running") { $job | Stop-Job }

Upvotes: 1

Related Questions