【问题标题】:Powershell foreach loop with if statements only evaluates first statement带有 if 语句的 Powershell foreach 循环仅评估第一个语句
【发布时间】:2026-01-06 18:10:02
【问题描述】:

所以我在下面有一个我的代码的 sn-p。基本上它从 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
    }
    }

【问题讨论】:

  • = 用于分配,而不用于比较。 [grin] 改用-eq
  • 另外,请查看switch 声明。它非常擅长在一个相当整洁的包中进行if/elseif/else 级联。

标签: powershell if-statement random foreach


【解决方案1】:

switch 语句比您使用的大量 IF 语句更漂亮且更易于使用。这是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 ? ?
}

【讨论】: