Powershell – Using Switch for Different Environments

I needed a way to automate installation of a script into different environments (e.g.Prod, Test, Dev)My server naming conventions are well defined so it made it easy.

The idea is the script runs on the computer I want it to run on (no powershell remoting or invoke-command here).

So the $InstallEnvironment variable is what I use later  on in the script .

this script fragment gets the computername from the environment variable COMPUTERNAME

It then sees if the $Computername is LIKE a particular pattern and if it is sets the $InstallEnvironment to that environment.

If it does not match any of the switch statements, it sets the $InstallEnvironment  to  “ServerNOTInEnvironment” , so that in the rest of the script I can error and return doing nothing.

$InstallEnvironment = $NULL

$Computername = $Env:COMPUTERNAME

switch ($Computername)

{

  {($_ -like "Server-P-*") -or ($_ -like "SRV-WWW-P-*") -or ($_ -like "SRV-ABC-P-*") } { $InstallEnvironment = "Prod" }

  {($_ -like "Server-E-*") -or ($_ -like "SRV-WWW-E-*") -or ($_ -like "SRV-ABC-E-*") } { $InstallEnvironment = "Train" }

  {($_ -like "Server-T-*") -or ($_ -like "SRV-WWW-T-*") -or ($_ -like "SRV-ABC-T-*") } { $InstallEnvironment = "Test" }

  {($_ -like "Server-D-*") -or ($_ -like "SRV-WWW-D-*") -or ($_ -like "SRV-ABC-D-*") } { $InstallEnvironment = "Dev" }

  {($_ -like "Server-A-*") -or ($_ -like "SRV-WWW-A-*") -or ($_ -like "SRV-ABC-A-*") } { $InstallEnvironment = "Alpha" }

  

  Default  { $InstallEnvironment = "ServerNOTInEnvironment" }

}

 

 

 

 

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.