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
    Posts
    • #183552
      Participant
      Topics: 1
      Replies: 0
      Points: -27
      Rank: Member

      Hi!

      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:

      
      function Get-BLUserName {
      [CmdletBinding()]
      Param
      ([Parameter(Mandatory=$true)]
      [ValidateNotNull()]
      [ValidateNotNullOrEmpty()]
      [object[]]$computers
      )
      for ($i = 0; $i -lt $computers.Length; $i++)
      {
      
      $temp = (Get-CimInstance -ClassName CIM_ComputerSystem -ComputerName $computers[$i].HostName -OperationTimeoutSec 1 -ErrorAction continue)
      
      if( $temp.UserName -ne $null )
      {
      (Get-ADUser -Identity $temp.UserName.Split("\")[1]).Name
      $temp.UserName
      $temp.Name
      $temp.Model + "`r`n" | fl
      
      }
      }
      }
      
      

       

      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: 8
      Replies: 1141
      Points: 3,927
      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: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_jobs?view=powershell-5.1

Viewing 1 reply thread
  • You must be logged in to reply to this topic.