1

看看下面的代码。如果我只用第一个“if”语句运行它,我会得到想要的结果。添加第二个“if”语句(如下所示),我没有得到想要的结果。这里有什么问题以及为什么 PowerShell 以两种不同的方式表现!

$CACHE_OS = ""
$OPERATINGSYSTEM = "WIN832_9200"

if ( $OPERATINGSYSTEM -match "WIN832" ) { $CACHE_OS = "WIN832" } else { $CACHE_OS = $OPERATINGSYSTEM }
if ( $OPERATINGSYSTEM -match "WIN864" ) { $CACHE_OS = "WIN864" } else { $CACHE_OS = $OPERATINGSYSTEM }

$CACHE_OS

仅供参考:将条件语句格式化为单行,以便于上面阅读和解释。

4

2 回答 2

4

这是预期的行为。我认为您可能误解了控制流程的进展方式。

$CACHE_OS = ""
$OPERATINGSYSTEM = "WIN832_9200"

if ( $OPERATINGSYSTEM -match "WIN832" )  # true
{
  $CACHE_OS = "WIN832"  # $cache_os set to "WIN832"
}
else
{
  $CACHE_OS = $OPERATINGSYSTEM
}

# at this point $cache_os has a value of "WIN832"

if ( $OPERATINGSYSTEM -match "WIN864" ) # false
{
  $CACHE_OS = "WIN864"
}
else # control goes here
{
  $CACHE_OS = $OPERATINGSYSTEM   # $cache_os is re-assigned, new value is "WIN832_9200"
}

$CACHE_OS  # output the current value ("WIN832_9200")

也许您的意思是使用elseif语句?

$CACHE_OS = ""
$OPERATINGSYSTEM = "WIN832_9200"

if ( $OPERATINGSYSTEM -match "WIN832" )
{
  $CACHE_OS = "WIN832"
}
elseif ( $OPERATINGSYSTEM -match "WIN864")
{
  $CACHE_OS = "WIN864"
}
else
{
  $CACHE_OS = $OPERATINGSYSTEM
}
于 2012-08-27T23:26:14.220 回答
0

它按预期工作。在第一个 IF 中,$OPERATINGSYSTEM 匹配“WIN832”,因此 $CACHE_OS 设置为“WIN832”,正如您所料,ELSE 语句列表未执行

在第二个 IF 中,$OPERATINGSYSTEM 不匹配“WIN832”,因此跳过了 IF 语句列表并开始执行 ELSE 部分,并为 $CACHE_OS 分配了 $OPERATINGSYSTEM 的值,即“WIN832_9200”。

于 2012-08-28T06:42:55.357 回答