Powershell Switch语句设置多个变量

时间:2012-07-30 19:26:09

标签: powershell

我正在将一些旧的VB脚本转换为Powershell。我试图使用Switch语句来设置多个变量。在Powershell中这可能吗?在VBS中,我的代码看起来像这样:

Select Case ENV
    Case "DEV"
        : SRCDRV  = "\\Server1" _
        : DESTDRV = "\\Server1\Folder1\"

    Case "TEST"
        : SRCDRV  = "F:" _
        : DESTDRV = "\\Server1\Folder2\"

    Case "PROD"
        : SRCDRV  = "F:" _
        : DESTDRV = "\\Server2\Folder2\"
End Select

我在PS中尝试了类似的东西,但它似乎没有设置变量。

switch ($cENV) {
    DEV { 
        $SRCDRV = "\\Server1"
        $DSTDRV = "\\Server2\Folder1\"
        break     
    }
    TEST {
        $SRCDRV = "\\Server1"
        $DSTDRV = "\\Server2\Folder2\"
        break
     }
    PROD {
        $SRCDRV = "\\Server1"
        $DSTDRV = "\\Server2\Folder2\"
        break
     }
}

当我检查DESTDRV或SRCDRV的值时,我收到错误消息:无法检索变量'$ SRCDRV',因为它尚未设置。关于我做错了什么想法?

2 个答案:

答案 0 :(得分:12)

当找到交换机的案例时,您的代码可以正常工作。 $ cENV的值可能与" DEV"," TEST"或" PROD"不匹配。添加默认开关案例并在没有匹配时执行某些操作,例如:

switch ($cENV) {
  DEV { 
    $SRCDRV = "\\Server1"
    $DSTDRV = "\\Server2\Folder1\"
    break     
  }
  TEST {
    $SRCDRV = "\\Server1"
    $DSTDRV = "\\Server2\Folder2\"
    break
  }
  PROD {
    $SRCDRV = "\\Server1"
    $DSTDRV = "\\Server2\Folder2\"
    break
  }
  default {
    throw "No matching environment for `$cENV: $cENV"
  }
}

答案 1 :(得分:9)

您是先设置$ cENV吗?

我正在运行上面那个确切的脚本:

$cENV = "DEV"
switch ($cENV) {
    DEV { 
        $SRCDRV = "\\Server1"
        $DSTDRV = "\\Server2\Folder1\"
    }
    TEST {
        $SRCDRV = "\\Server1"
        $DSTDRV = "\\Server2\Folder2\"
     }
    PROD {
        $SRCDRV = "\\Server1"
        $DSTDRV = "\\Server2\Folder2\"
     }
}
$SRCDRV

它正在回归

\\Server1