#循环语句
#简介
循环用于重复执行一段代码。PowerShell 提供 for、foreach、while、do...while 和 do...until 等循环语句,并支持 break 和 continue 控制流程。
#for
for 循环适合已知循环次数的情况:
for ($i = 1; $i -le 5; $i++) {
Write-Output "i = $i"
}
i = 1
i = 2
i = 3
i = 4
i = 5
三个部分依次是:初始化、条件、迭代。
#foreach
foreach 用于遍历数组或集合:
> $fruits = @("apple", "banana", "cherry")
> foreach ($fruit in $fruits) {
>> Write-Output $fruit.ToUpper()
>> }
APPLE
BANANA
CHERRY
#while
while 在条件为真时反复执行:
> $i = 0
> while ($i -lt 3) {
>> $i++
>> Write-Output $i
>> }
1
2
3
如果条件一开始就为假,循环体一次也不会执行。
#do...while 与 do...until
do 循环先执行一次循环体,再判断条件。
do...while 在条件为真时继续:
> $i = 0
> do {
>> $i++
>> Write-Output $i
>> } while ($i -lt 3)
1
2
3
do...until 在条件为真时停止:
> $i = 0
> do {
>> $i++
>> Write-Output $i
>> } until ($i -ge 3)
1
2
3
两者的区别只是继续/停止的判断方向相反。
#范围运算符
.. 可以生成一个整数范围,常与 foreach 配合使用:
> foreach ($n in 1..5) {
>> Write-Output $n
>> }
1
2
3
4
5
范围也可以倒序:
> 5..1
5
4
3
2
1
#break 与 continue
break立即结束整个循环。continue跳过本次迭代,进入下一次循环。
> foreach ($n in 1..5) {
>> if ($n -eq 3) { continue }
>> if ($n -eq 5) { break }
>> Write-Output $n
>> }
1
2
4
#ForEach-Object 与循环的区别
ForEach-Object 是管道命令,逐个处理从管道传入的对象:
> 1..5 | ForEach-Object {
>> if ($_ -eq 3) { return }
>> $_
>> }
1
2
4
5
主要区别:
| 特性 | foreach 语句 | ForEach-Object |
|---|---|---|
| 类型 | 语言语句 | 管道命令 |
| 数据来源 | 内存中的集合 | 管道流 |
| 大结果集 | 需要先加载整个集合 | 可以流式处理 |
break | 支持 | 不支持,需用 return 跳过 |
continue | 支持 | 不支持,需用 return 跳过 |