Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go to next item in ForEach-Object

Tags:

powershell

I have a PowerShell script that does some checks on all Domain Admins in a number of domains. For each user account a number of checks are preformed. When one of them fails the script should go to the next admin in the list.

I currently have something like this (simplified):

Get-QADGroupMember "Domain Admins" | Select-Object SamAccountName | ForEach-Object {      #Do something     if(!ThisCheckIsOK)     {         break;     }      #Do something else     if(ThisCheckIsNotOK)     {         break;     }      ... } 

This stops the whole script. Is there a way to go to the next element?

$foreach.movenext() does not work since $foreach is null.

like image 523
Bart De Vos Avatar asked Dec 07 '11 09:12

Bart De Vos


People also ask

How do you skip a record in ForEach?

Use the continue statement to skip to the next iteration. Show activity on this post. Rather than throwing an exception, instead you should try and check if the user is valid first.

How do I break a ForEach loop in PowerShell?

The Break statement is used to exit a looping statement such as a Foreach, For, While, or Do loop. When present, the Break statement causes Windows PowerShell to exit the loop. The Break statement can also be used in a Switch statement.

What is the difference between ForEach and ForEach-Object?

Difference between FOREACH LOOP AND FOREACH-OBJECTThe ForEach statement loads all of the items upfront into a collection before processing them one at a time. ForEach-Object expects the items to be streamed via the pipeline, thus lowering the memory requirements, but at the same time, taking a performance hit.

What is ForEach-Object in PowerShell?

Description. The ForEach-Object cmdlet performs an operation on each item in a collection of input objects. The input objects can be piped to the cmdlet or specified using the InputObject parameter. Starting in Windows PowerShell 3.0, there are two different ways to construct a ForEach-Object command. Script block.


1 Answers

You just have to replace the break with a return statement.

Think of the code inside the Foreach-Object as an anonymous function. If you have loops inside the function, just use the control keywords applying to the construction (continue, break, ...).

like image 196
Thierry Franzetti Avatar answered Sep 18 '22 15:09

Thierry Franzetti