Powershell

How to Exit From ForEach-Object in PowerShell

The “ForEach-Object” command in PowerShell is used to loop or iterate through the collection of input objects. The input objects are then sent using the piping method to the cmdlet. Similarly, sometimes we need to exit from the “ForEach-Object” in PowerShell to stop the script from further execution.

This tutorial will present a thorough guide to exit from PowerShell ForEach-Object.

How to Exit From ForEach-Object in PowerShell?

The enlisted approaches can be used to exit from ForEach-Object in PowerShell:

    • if” Statement
    • break” Statement

Method 1: Exit From ForEach-Object in PowerShell Using “if” Statement

The “if” statement can be used to exit from a “ForEach-Object” in PowerShell. For a more detailed explanation, check out the given example.

Example

Let’s take a look at this example to exit from “ForEach-Object” using the “if” statement:

$Val = "Brakes","Wheels","Window","","Staring"
$val | ForEach-Object{
 if($_ -eq ""){
 break;
}
 Write-Output "The car has $_."
}

 
In the stated example:

    • First, we have created a variable “$val” and assigned multiple values to it.
    • In the next line, first, we added the “$val”, and after that, used the pipeline “|” to take the output from the previous value and transform it as the input to the next “ForEach-Object” cmdlet.
    • Now, when the condition is evaluated as “true”, the break statement will exit the For-Each object execution:

 

Method 2: Exit From ForEach-Object in PowerShell Using the “break” Statement

The “break” statement can be used to take an exit from the “ForEach-Object” in PowerShell. This statement can be utilized to break the loops or iterations.

Example

Let’s consider this example to exit from “ForEach-Object” using the “break” statement:

$objects = "Brakes","Wheels","Windows"
$Break = $False;
$objects | Where-Object { $Break -eq $False } | ForEach-Object {
 $Break = $_ -eq "Wheels";
 Write-Output "The car has $_.";
}

 
According to the given code:

    • We have used the “break” statement and specified a condition.
    • When the added condition is satisfied, the script will be stopped, and the resultant message will be displayed on the terminal:

 

That was all about exiting the ForEach-Object in PowerShell.

Conclusion

To exit from “ForEach-Object” in PowerShell, two methods can be used, including “break” and “if”. Both of the methods will exit from PowerShell “ForEach-Object” loop when the condition specified by them becomes true. This tutorial has presented a thorough guide on how to exit PowerShell “ForEach-Object”.

About the author

Muhammad Farhan

I am a Computer Science graduate and now a technical writer who loves to provide the easiest solutions to the most difficult problems related to Windows, Linux, and Web designing. My love for Computer Science emerges every day because of its ease in our everyday life.