Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell Switch Statement to Set Multiple Variables

Tags:

powershell

I am in the process of converting some old VB script to Powershell. I am trying to use a Switch statement to set multiple variables. Is this possible in Powershell? In VBS my code would look something like this:

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

I have tried something similar in PS, but it doesn't seem to set the variables.

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

When I check the value of either DESTDRV or SRCDRV I get an error saying: The variable '$SRCDRV' cannot be retrieved because it has not been set. Any ideas on what I'm doing wrong?

like image 704
mack Avatar asked Jul 30 '12 19:07

mack


1 Answers

Your code works when a case is found for the switch. $cENV probably has a value that does not match "DEV", "TEST", or "PROD". Add a default switch case and do something when you don't have a match, example:

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"
  }
}
like image 96
dugas Avatar answered Sep 29 '22 19:09

dugas