powershell@foreach@foreach-object@continue的行为
文章目录
powershell@foreach@foreach-object@continue的行为
ref
- about Continue - PowerShell | Microsoft Learn
- powershell - Why does ‘continue’ behave like ‘break’ in a Foreach-Object? - Stack Overflow
foreach@foreach-object
-
about Foreach - PowerShell | Microsoft Learn
- powershell/module/microsoft.powershell.core/about/about_foreach
- 这是一个powershell 遍历可迭代对象的基本语法,属于循环(loop)中的一种
- 不妨称它为
loop-foreach
-
ForEach-Object (Microsoft.PowerShell.Core) - PowerShell | Microsoft Learn
- powershell/module/microsoft.powershell.core/foreach-object
- 这是一个powershell cmdlet(powershell命令),不是一种循环,可能是基于基本语法编制而成的功能性命令
- 不妨称它为
cmdlet-foreach
-
这一点区别将会在使用continue的时候显现出来
- continue放在在某个Loop中时(比如foreach),那么它的行为就像c语言那样
- 如果是放在foreach-object(有时候简写为foreach,区分loop-foreach),充当
scriptblock
- 这时候,会尝试跳过最近的loop语法层(如果存在的话)
-
What is a PowerShell command? - PowerShell | Microsoft Learn
What is a cmdlet?
- Cmdlets are native PowerShell commands, not stand-alone executables.
- Cmdlets are collected into PowerShell modules that can be loaded on demand.
- Cmdlets can be written in any compiled .NET language or in the PowerShell scripting language itself.
break@continue
案例
foreach@continue
loop-foreach
-
Write-Output 'foreach-loop' $l = 1..5 foreach ($elem in $l) { if ($elem -eq 3) { continue; # not return here } Write-Output $elem }
cmdlet-foreach
-
Write-Output 'foreach-object(cmdlet)' 1..5 | ForEach-Object { if ($_ -eq 3 ) { return #not continue here } Write-Output $_ }
运行结果
-
foreach-loop 1 2 4 5 foreach-object(cmdlet) 1 2 4 5
其他方案
- 加一层
if-else
可以在cmdlet中模拟continue
的字面行为- 但是这增加了不必要的代码
- 而且不够优雅
- 做过滤的时候
where-object
有时候比foreach-object
更加合适
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2021-05-23 java_计算一个人从出生日期开始到他参加高考的时间间隔有多少天(假设是18岁参加高考)