下面舉兩個例子:
$array=7..10
foreach ($n in $array)
{
$n*$n
}
#49
#64
#81
#100
foreach($file in dir c:\windows)
{
if($file.Length -gt 1mb)
{
$File.Name
}
}
#explorer.exe
#WindowsUpdate.log
這里只為了演示foreach,其實上面的第二個例子可以用Foreach-Object更簡潔。
PS C:\Powershell> dir C:\Windows | where {$_.length -gt 1mb} |foreach-object {$_.Name}
explorer.exe
WindowsUpdate.log