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 @   xuchaoxin1375  阅读(4)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2021-05-23 java_计算一个人从出生日期开始到他参加高考的时间间隔有多少天(假设是18岁参加高考)
点击右上角即可分享
微信分享提示