Break/continue in a foreach loop Powershell

How to use break and continue in a foreach loop in Powershell

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# Use break to get out of the loop

$files = Get-ChildItem C:\PSfolder -File
foreach ($file in $files)
{
  if ($file.Name -like "*.ps1")
  {
    $file.Name
    break  # exit the foreach loop
  }
}


# Use continue to skip the rest of a loop but go onto the next iteration

$files = Get-ChildItem C:\PSfolder -File
foreach ($file in $files)
{
  if ($file.Name -like "*.ps1")
  {
    $file.Name
    continue  # exit and go tho the next item in foreach
    "This code will be skipped"
  }
  "This isn't a powershell file: $file"
}