首页 > 解决方案 > 带有 if 语句的 Powershell foreach 循环仅评估第一个语句

问题描述

所以我在下面有一段代码。基本上它从 1 循环到用户输入。每个循环它都会生成一个从 1 到 4(含)的随机数,然后根据该数字将特定的 Word 文档打印到默认打印机。

如果我只运行没有所有 if / elseif 语句的代码,只打印 $ran 的值,那么它可以完美运行。

但是,一旦我将 if / elseif 语句放入其中,它只会打印文件号 1.docx。

任何想法为什么当我使用 if / elseif 语句时 $ran 的值似乎保持为 1?

代码 -

1..$count | foreach { $ran = random -Minimum 1 -Maximum 5
    if ($ran = 1) {
    Start-Process -FilePath "file1" -Verb Print
    Wait-Process "WINWORD"
    }
Elseif ($ran = 2){

    Start-Process -FilePath "file2" -Verb Print
    Wait-Process "WINWORD"
    }
elseif ($ran = 3){

    Start-Process -FilePath "file3" -Verb Print
    Wait-Process "WINWORD"
    }
elseif ($ran = 4){

    Start-Process -FilePath "file4" -Verb Print
    Wait-Process "WINWORD"
    }
else {

    Write-Output "Something went wrong!"
    pause
    }
    }

标签: powershellif-statementrandomforeach

解决方案


与您使用的大量 IF 语句相比,switch 语句更漂亮且更易于使用。switch这是/的语法

$x = Get-Random -Minimum 1 -Maximum 7
    switch ($x)
    {
        1 {"x was 1"}
        {$_ -in 2,3} {"x was 2 or 3"}
        4 {"x was 4"}
        Default {"x was something else"}
    }

您可以非常简单地指定比较,只需匹配变量的值。您也可以将脚本块用于更复杂的逻辑。最后,Default处理其他语句未明确解决的任何其他问题。

以下是如何开始使用 switch 语句重写代码。

1..$count | foreach { 
    $ran = random -Minimum 1 -Maximum 5
    switch ($ran){
        1{
        Start-Process -FilePath "file1" -Verb Print
        Wait-Process "WINWORD"
    }
        2{
        Start-Process -FilePath "file2" -Verb Print
        Wait-Process "WINWORD"
    }
    #finish the rest here  
}

推荐阅读