【发布时间】: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