代码之家  ›  专栏  ›  技术社区  ›  Vippy

PowerShell:条件“if”语句的异常行为

  •  1
  • Vippy  · 技术社区  · 12 年前

    看看下面的代码。如果我只运行第一个“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 回复  |  直到 12 年前
        1
  •  4
  •   latkin    12 年前

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

    $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
    }
    
        2
  •  0
  •   Shay Levy    12 年前

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

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