PowerShell:条件“if”语句的奇怪行为

时间:2012-08-27 22:18:47

标签: powershell match behavior conditional-statements

看看下面的代码。如果我只使用第一个“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

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

2 个答案:

答案 0 :(得分: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
}

答案 1 :(得分:0)

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

在第二个IF中,$ OPERATINGSYSTEM与“WIN832”不匹配,因此跳过IF语句列表并且 ELSE部分启动,并且$ CACHE_OS被赋值为$ OPERATINGSYSTEM,这是“WIN832_9200”。