How to abort iteration in forloop and continue iterating


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 {
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.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?

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: about Jobs - PowerShell | Microsoft Docs