【问题标题】:Not able to skip the 1st iteration in foreach-object using continue statement.Please suggest无法使用 continue 语句跳过 foreach-object 中的第一次迭代。请建议
【发布时间】:2019-09-27 07:32:16
【问题描述】:

您好,我有 powershell,我正在使用 foreach 对象,并且希望始终跳过第一次迭代。我也在使用 continue 语句。但是 continue 的当前行为就像 break 一样。如果我在这里做错了什么,请提出建议。

下面是示例代码。

$xmlfile = 'D:\testdirecotry\sample.xml'
[xml]$xmlcontent = (Get-Content $xmlfile)
$folderprefix = 'plm_z'
$regex = '<!--__AMAZONSITE id="(.+?)" instance="(.+?)"__-->'
$i=0

(Get-Content $xmlfile) | select-string -Pattern $regex | ForEach-Object {

    write-host "Test Iterartion"

    if($i -eq 0)
    {
        write-host "entering if loop"
        write-host $i
        $i++
        write-host $i
        continue
    }
    else
    {
        write-host "entering else loop"
        write-host $_   
        $pscustomobject=@(
            # write-host $_
            $id = $_.Matches.Groups[1].Value        
            $instance = $_.Matches.Groups[2].Value      

            write-host "Do Something"

        )
    }

}

【问题讨论】:

    标签: powershell


    【解决方案1】:

    跳过第一个对象的更简单方法可能是在管道中使用Select-Object

    Get-Content $xmlfile |
      Select-string -Pattern $regex |
      Select-Object -Skip 1 |
      ForEach-Object {
        ...
    

    【讨论】:

      猜你喜欢
      • 2011-08-08
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 2013-10-03
      • 2021-12-26
      • 1970-01-01
      • 2012-01-10
      • 1970-01-01
      相关资源
      最近更新 更多