How to use PowerShell break statement in foreach loop?

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


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


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.