How to abort iteration in forloop and continue iterating

Welcome Forums General PowerShell Q&A How to abort iteration in forloop and continue iterating

Viewing 1 reply thread
  • Author
    • #183552
      Topics: 1
      Replies: 0
      Points: -27
      Rank: Member


      I’m quite new to Powershell scripting butĀ  what I want to accomplish is this: Find out which user sits at a certain computer.

      I am using Get-DhcpServerv4Lease to filter out the subnets I am interested in.

      I get the users information by this script I have made:


      The problem is that some computers have not restarted since I enabled a WinRM GPO (have confirmed that it is working already) so I get this message when running the Get-Ciminstance: “Get-CimInstance : WinRM cannot complete the operation.”

      In some cases this can take up to 40 seconds. How do I abort the current iteration?

      When I useĀ  Get-CimInstance -ClassName CIM_ComputerSystem -ComputerName $computers[$i].HostName -OperationTimeoutSec 1 -ErrorAction Stop, it immediately stops when it discovers the error – I would it to continue directly to the next iteration in the loop instead of it evaluating a long time when I use “-ErrorAction SilentlyContinue”.


      Any ideas? Try, catch?

    • #183558
      Senior Moderator
      Topics: 9
      Replies: 1309
      Points: 4,783
      Helping Hand
      Rank: Community Hero

      you could use background jobs here.

      Have a job created for each computer in a loop using Start-Job cmdlet and finally use Wait-Job to wait for the completion. Hence it will act like a fire and forget model and then evaluate the job result later.

      see this doc for more about jobs:

Viewing 1 reply thread
  • The topic ‘How to abort iteration in forloop and continue iterating’ is closed to new replies.