Scripting Games 2011 Commentary: II–using a switch parameter
A switch parameter does exactly what it says. It switches on some piece of code in your function.
Using a switch parameter seems to be misunderstood. I saw a lot of code like this during the games.
| 001 002 003 004 005 006 007 008 009 010 011
| function testswitch { param ([switch]$all=$false) if ($all -eq $false){ get-process | sort CPU -Descending | select -First 5 } else { get-process | sort CPU -Descending } } |
Our function is designed to display the top 5 CPU using processes currently running on the system. That is the default behaviour.
A switch parameter is defined. If the switch is used we get all processes sorted by CPU usage.
This code will work but it involves more coding than is necessary. This can introduce bugs – more typing = more chance for mistakes (especially for me)
There are a few things to remember:
- switches are boolean (true of false)
- switch paramters default to false – when we use the switch its value changes to true
- if statement tests have to produce a boolean result
This means we can change our code to this
| 001 002 003 004 005 006 007 008 009 010 011
| function testswitch2 { param ([switch]$all) if ($all){ get-process | sort CPU -Descending } else { get-process | sort CPU -Descending | select -First 5 } } |
We leave the switch parameter to default to false
The test on the if statement produces a boolean – $all is a boolean so we can test its value directly.
The order of the statements is changed slightly. If $all is true (switch is used) then we produce all results otherwise we produce just first 5
I always find it easier to work with an if statement where the first resulting script block occurs if the test is true. We could write the if block as
if (-not($all)){
get-process | sort CPU -Descending | select -First 5
}
else {
get-process | sort CPU -Descending }
but I find that more confusing when I come back to it.
Points to remember:
- switches are boolean and default to false
- can test booleans directly with if - - if ($variable){. . . }