1

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

1 Answers1

1

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 }
Adam
  • 3,891
  • 3
  • 19
  • 42
  • I think, it's the right track, just the wrong train. A good part of a day i spent making that work. For some reason variables don't get assigned inside of a scriptblock for me, ie `$Reg = [Microsoft.Win32.RegistryKey]` is always empty. I made it work at some point when i run `$Reg = invoke-command -scriptblock {receive-job -job $job}`, but it only works sometimes. Other times job is in a 'completed' state, but no output is there. Any clues? – snakePlantLeaf Apr 09 '18 at 08:37
  • You pass variables to a script block executed by Invoke-Command as arguments to the script block. Invoke-Command -Scriptblock { $x = $args[0]; ... } -ArgumentList $foo. Check the help page for more details. – Adam Apr 10 '18 at 13:41
  • Without seeing your code, I'm just throwing darts as to why it's not working consistently. I'd probably use a few Write-Host calls to trace the state of values in the block. Maybe open that up as a separate question. – Adam Apr 10 '18 at 13:45
  • Gonna ask a different question about jobs, i guess. Really got stuck with this. Thanks anyway! After i figure out jobs, i will come back here ;) – snakePlantLeaf Apr 11 '18 at 15:00