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
.
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.
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.
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.
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.
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
, ...).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With