8

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?

2 Answers 2

13

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"
  }
}
Sign up to request clarification or add additional context in comments.

Comments

11

Are you setting $cENV first?

I'm running that exact script above like this:

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

And it's returning

\\Server1

2 Comments

$cENV probably has some value, otherwise he would get an error message that $cENV cannot be retrieved.
Thanks, you're right, if I set $cENV to "DEV" it does return the correct value. I didn't think to try setting it specifically. The $cENV variable is being set by a function that determines the script file's location. If I put the switches, "DEV", "TEST" and "PROD", in quotation marks, it works like a champ. Thanks very much for your help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.