Using Param and switch block to set variables


I’m trying to create a function that when called will set the variables accordingly depending on which parameter is called at the time:

Function Select-Environment {
Param (
[Parameter(ParameterSetName = 'Tier1')]

[Parameter(ParameterSetName = 'Tier2')]


switch ($PSCmdlet.ParameterSetName) {
'Tier1' {
$ComTierServers = "Server1","Server2","Server3"
$AppTierServers = "Server4","Server5","Server6"
$WebTierServers = "Server7","Server8","Server9"
'Tier2' {
$ComTierServers = "Server10","Serve11","Server13"
$AppTierServers = "Server14","Server15","Server16"
$WebTierServers = "Server17","Server18","Server19"

Select-Environment -Tier1

There’s no error when I run this but calling $ComTierServers doesn’t return the array of servers.

Am I missing something obvious here?


This is because of variable scoping. The variables are created in the function and has the life only inside the function as they are local scoped by default. You can either explicitly scope them as $Script:ComTierServers or return them from the function and capture it in a variable.

Spot on thanks. I have actually come across this before in a previous script yonks ago but just didn’t think of it this time. I haven’t used ParameterSets with switch statements that much so thought I was going about it the wrong way instead of thinking of variable scoping.

Thanks again.