I wanted to use an array of strings in PowerShell as a sort of “key” for defining Azure Resource Groups. But I needed to process just some of the elements of the array. A foreach
loop is the obvious first choice:
$ArrayOfStrings = @("FirstAzureResourceGroup", "SecondAzureResourceGroup", "ThirdAzureResourceGroup") foreach ($s in $ArrayOfStrings) { if ($s -eq "FirstAzureResourceGroup") { "Process the first matched string" } }
This isn’t bad, of course. However, in the case when you don’t want to do the same thing to all variables in the array or you only want to process some of them, you need to code logic like you see above in the if
statement.
I’ve stumbled across something significantly more elegant: using the PowerShell switch
statement. The documentation for switch
only says that the statement can, among other capabilities, evaluate a “value”. It’s unclear if that includes arrays.
That’s a shame because switch
does work with arrays and does it very nicely. Consider this alternative to the code above. Using switch
eliminates a series of if
statements in the foreach
loop.
$ArrayOfStrings = @("FirstAzureResourceGroup", "SecondAzureResourceGroup", "ThirdAzureResourceGroup") switch ($ArrayOfStrings) { "SecondAzureResourceGroup" { "Process the first matched string" } "ThirdAzureResourceGroup" { "Process the second matched string" } }
If you watch this code in a debugger, you’ll see that PowerShell loops through all elements in the array, as you might expect. So I don’t think using switch
with arrays is any more efficient. But it allows you to specify easily a process block that’s associated with a specific value in an array. The code just looks better to me than nested if
statements.
Note that I didn’t specify a default
clause in the sample above. That’s because I only wanted to process specific elements in the array and no others. If you do specify default
PowerShell will execute the process block for each unmatched element in the array.
I hope you enjoy this — and if you read this far, yes that’s a piece of Toblerone. Every time I eat it (it’s my favorite), I think of arrays of chocolate just waiting to be processed by the PowerShell switch
statement.
Leave a Reply