问题是否在foreach循环内继续执行

时间:2019-01-06 17:31:07

标签: powershell

我有以下for循环。我的问题是,如果我对第一个if语句使用continue语句,那么第二个if语句(saveto)无法正常工作。据我所知,我假设存在逻辑错误。 它的工作流程如下:

-All参数为null且SaveTo参数不为null,将执行附件过滤器,第二个if语句将执行。

-All参数不为null且SaveTo参数不为null,附件过滤器将不执行,第二个if语句将执行。

foreach ($attachment in $attachments.value) {
    # weed out unwanted attachments
    # Use the All siwtch to include them
    If (!$All) {
        If ($attachment.Size -lt 100000 -and $attachment.contentType -like '*image*') {
            #images from less then 100kb
            continue
        } ElseIf ($attachment.contentType -eq 'application/octet-stream' ) {
            #bin files
            continue
            }
    }

    If ($SaveTo) {
        $timestamp = $attachment.DateTimeLastModified.Replace(':','')
        $path = "$SaveTo\$timestamp`_$($attachment.name)"
        #$path = "C:\path\" + $attachment.Name

        $Content = [System.Convert]::FromBase64String($attachment.ContentBytes)
        Set-Content -Path $path -Value $Content -Encoding Byte  
    }

}

2 个答案:

答案 0 :(得分:1)

通过使用$saveto语句,如果$all不是$null,则专门指示代码跳过Continue部分。

  

继续

     

返回到程序循环的顶部,仅跳过该循环的迭代。

     

在For,ForEach或While循环中,您可以将continue语句添加到   跳到最里面的循环的顶部。

     

示例

     

数到10但错过了5:

$i =0
 while ($i -lt 10)
     {
       $i +=1 
       if ($i -eq 5) {continue}
       Write-Host $i
     }
     

来源:SS64 - Continue statement

Continue语句中只能使用Switch退出循环的情况。在这种特定情况下,Continue语句将指示您要跳过剩余条件块并评估当前Switch中的下一个条件。

参考

SS64 - Switch statement

答案 1 :(得分:0)

那就是continue语句的作用:跳回到foreach循环的开始,并从下一个$ attachment开始。还here

相关问题