powershell - 带有 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
}
}
解决方案
与您使用的大量 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
}
推荐阅读
- android - 获取空对象错误以在 recyclerView 中使用多个布局
- mongoose - 需要一个使用带静态或方法的 mockingoose 的示例
- linux - 如何制定正确的 iptable 规则,如浏览器端口配置
- clojure - 通过 Clojure 中值列表中的第一个元素获取键
- api - 在 React Native fetch 方法中解析 JSON 不起作用
- javascript - 从 ReactJS 中的其他组件打开模式
- php - foreach 在 while 循环中返回重复数据
- javascript - WebStorm 和控制台在执行上的区别
- javascript - 在 Ionic 和 Cordova 中构建 Android APK
- android-fragments - 在后台运行的android片段