Syntax error How to use PowerShell break statement in foreach loop?

How to use PowerShell break statement in foreach loop?



You can use the PowerShell Break statement with the foreach loop as mentioned below.

Example

foreach($obj in (Get-ChildItem D:\Temp)){
   Write-Output $obj
   if($obj.Name -eq "cars.xml"){Break}
}

Output

Directory: D:\Temp
Mode       LastWriteTime       Length Name
----       -------------       ------ ----
d-----     13-12-2019                 09:52GPO_backup
d-----     24-11-2018 11:31           LGPO
-a----     27-01-2020 22:21     13962 Alias1
-a----     26-01-2020 19:20     13818 aliases.txt
-a----     07-05-2018 23:00301  cars.xml

In the above example, when the file name matches the cars.xml then the loop gets terminated.

Updated on: 2020-03-12T07:27:28+05:30

652 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements