I thought if you use a switch parameter you don’t have to specify whether the parameter is true or false, but rather just using the parameter itself tells PowerShell that it is true.
For instance, if I do something like in the following example, PowerShell responds with an error wanting the parameter to be specified explicitly as $false:
Function Do-Something
{
param
(
[switch]param1
)
}
Do-Something -param1
However, if I do this, it works fine:
Function Do-Something
{
param
(
[switch]param1
)
}
Do-Something -param1 $true
So we have to state that the parameter be true if we want it to be used? I thought just stating the parameter tells PowerShell that it is true?
For the most part, you’re correct. Switch parameters, in their general usage, are $false if you don’t specify them on the command line, and are $true if you do specify them on the command line. They don’t take any arguments (again, in the general usage case):
function MyFunction([switch] $MySwitch) { }
MyFunction # $MySwitch is $false
MyFunction -MySwitch # $MySwitch is $true
However, sometimes you do need to be able to pass in a specific value for the switch parameter, either because you’re passing it on from one function to another (such as in a proxy function), or because you need to deliberately set a switch to $false (which is rare, but you’ll sometimes see this with -Confirm:$false . In this case, setting Confirm explicitly to false causes it to override the behavior of the $ConfirmPreference variable, which would otherwise be used.) When you do need to pass an argument to a switch parameter, you need place a colon between the parameter and its argument, like so:
MyFunction -MySwitch:$false
If you’re using splatting with a hashtable, you can just assign a value of $true or $false to that key of the hashtable, and PowerShell knows what to do with it:
firstly, neither of those examples work for me from just copy/pasting as you’ve neglected the ‘$’ in the parameter declaration so there is a general error and the function cannot be defined. The function should be like:
Function Do-Something
{
param
(
[switch]$param1
)
}
Do-Something -param1
Can you provide the exact error message you’re getting?