Win10 Powershell-简单的If / Elseif是否取决于条件顺序? [英] Win10 Powershell - Simple If/Elseif Depends on Condition Order?

查看:178
本文介绍了Win10 Powershell-简单的If / Elseif是否取决于条件顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个部署脚本,该脚本检查OS的主要版本,然后基于该版本运行命令。我可以使用 [System.Environment] :: OSVersion.Version.Major 很好地抓住它,但是当我尝试在if / elseif语句中使用它时,我总是得到

I'm attempting to write a deployment script that checks the OS major version, then runs command based on that. I can grab that just fine with [System.Environment]::OSVersion.Version.Major, but when I attempt to use that in an if/elseif statement, I always get the first condition, and somehow the variable changes.

所以我要测试的代码是(使用Windows 10机器):

So the code I'm working with to test is this (using a Windows 10 machine):

$OS_VERSION=$([System.Environment]::OSVersion.Version.Major)

if ($OS_VERSION = 6) {
  Write-Output "OS Version is $OS_VERSION"
  # Do stuff...
} elseif ($OS_VERSION = 10) {
  Write-Output "OS Version is $OS_VERSION"
  # Do different stuff..
}

我注意到,当我切换条件的顺序时,它按预期运行,甚至更令人沮丧的是,该语句在Windows 7计算机上运行得很好。

这是我缺少的Powershell的错误/怪癖,还是我在做愚蠢的事情?

推荐答案

我认为我会写出来,因为我能比我的评论更好地解释它。当您输入一个表达式而不分配它时,它将输出到管道。在这种情况下

I thought I'd write this out since I can explain it better than my comment. When you enter an expression without assigning it, it gets output to the pipeline. In this case

if ($OS_VERSION = 6) {

是一个表达式(因为 if 语句计算表达式以获取布尔值以采取行动)。如果在交互式提示符下输入时将其包装在括号中,它将输出变量在分配变量的同时分配的内容,就像

is an expression (since the if statement evaluates expressions for a boolean value to take action). If you wrap this in parentheses when entered at an interactive prompt, it'll output what the variable assigns at the same time as assigning the variable, much like

6 | Tee-Object -Variable OS_VERSION

将是 b,或者 -PassThru 启用某些cmdlet:

would, or a -PassThru switch on some cmdlets:

> ($Test = 6)
>> 6
> $Test
>> 6

所以您在这里所做的就是始终将该变量分配给 6 的值为 true ,因为如果是真实且非-zero是 true 。您需要的是 -eq 比较运算符

So what you're doing here is always assigning that variable to 6 which evaluates to true since if is truthy and non-zero is true. What you need is the -eq comparison operator:

if ($OS_VERSION -eq 6) {






可以从以下命令中找到更多信息:


More information can be found from the following command:

Get-Help -Name about_Comparison_Operators

这篇关于Win10 Powershell-简单的If / Elseif是否取决于条件顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆