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

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

问题描述

我正在尝试编写一个部署脚本来检查操作系统主要版本,然后基于该版本运行命令.我可以用 [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

将,或 -PassThru 开启某些 cmdlet:

would, or a -PassThru switch on some cmdlets:

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

所以你在这里所做的是 always 将该变量分配给 6 其评估结果为 true 因为 if 是真实的,非零是 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天全站免登陆