Switch Parameter

Introduction

The Switch parameter in PowerShell is a very useful feature. The big advantage of using the Switch parameter is that it can make your scripts much more concise and easier to read. In this blog post, we will take a look at how to use the Switch parameter, some best practices, and when you should use it.

What and How to use Switch Parameter

Switch parameter is a parameter that does not require an argument. It behaves like a toggle. By default, when an argument is not supplied, the default value is true. But, we can supply an argument explicitly, it must be true or false.

Below script is an example how to use Switch parameter. The script has two parameters which are Num and Even. Num is a mandatory parameter while Even is a switch parameter.


param (
    [Parameter(Mandatory = $true)]
    [int]
    $Num,
    
    [switch]
    $Even
)

if ($Even) {
    $counter = 1
    while ($counter -le $Num) {
        if($counter % 2 -eq 0) {
            Write-Host $counter
        }

        $counter++
    }
}else {
    $counter = 1
    while ($counter -le $Num) {
        Write-Host $counter

        $counter++
    }
}

Now, If we don’t pass Even parameter like .\test3.ps1 -Num 10, it will give below output that print numbers from 1 to 10.


Output:
1
2
3
4
5
6
7
8
9
10

If, for example, we pass Even parameter like .\test3.ps1 -Num 10 -Even, it will only print even numbers within 1 to 10 inclusively.


Output:
2
4
6
8
10

The effect of the latter executed script is the same with .\test3.ps1 -Num 10 -Even:$true. But, if we supply false to Even parameter, then the effect will be the same with the former executed script.

Executing .\test3.ps1 -Num 10 -Even:$true will result to below output.


Output:
2
4
6
8
10

Executing .\test3.ps1 -Num 10 -Even:$false will result to below output.


Output:
1
2
3
4
5
6
7
8
9
10

Conclusion

The Switch parameter is a useful parameter type in PowerShell that allows a parameter to be treated as Boolean switches. When used correctly, it can make your scripts more readable and easier to understand.