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
  • 2
    In powershell type: Get-Help about_Jobs Commented Apr 5, 2018 at 15:05

1 Answer 1

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 }
Sign up to request clarification or add additional context in comments.

4 Comments

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?
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.
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.
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 ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.