You probably know that the Switch statement checks against a value and returns whatever you have defined for this condition like so:
function Get-Name($number) {
switch ($number) {
1 { "One" }
2 { "Two" }
3 { "Three" }
default { "Other" }
}
}
switch ($number) {
1 { "One" }
2 { "Two" }
3 { "Three" }
default { "Other" }
}
}
Get-name 1
Get-Name 100
But did you know that you can assign the result from Switch to a variable directly by simply placing Switch into $()?
function Get-Name($number) {
$result = $(switch ($number) {
1 { "One" }
2 { "Two" }
3 { "Three" }
default { "Other" }
})
$result = $(switch ($number) {
1 { "One" }
2 { "Two" }
3 { "Three" }
default { "Other" }
})
"The result is: $result"
}
Get-name 1
Get-Name 100
In PowerShell V2, the $() workaround isn't even necessary.