powershell@foreach@foreach-object@continue的行为

powershell@foreach@foreach-object@continue的行为

ref

foreach@foreach-object

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更加合适
posted @ 2024-05-23 17:11  xuchaoxin1375  阅读(10)  评论(0)    收藏  举报  来源