3

In the below example I've got an IF statement to determine which parameters send to Demo when called recursively. If $y were a boolean value rather than a switch I could simply call Demo -x $x -y $y; but as a switch that's not a viable option.

function Demo {
    [CmdletBinding()]
    param (
        [int]$x
        ,[switch]$y
    )
    process {
        $x--
        if ($x -gt 0) {
            "$x - $($y.IsPresent)"
            if($y.IsPresent) {
                Demo -x $x -y
            } else {
                Demo -x $x
            }
        }
    }
}
Demo 10 -y
Demo 10

Question

Is the above the correct way to handle this scenario, or does a cleaner option exist?

JohnLBevan
  • 22,735
  • 13
  • 96
  • 178

1 Answers1

5

You can force a switch parameter by calling it like this: -Switch:$true (redundant in most cases) or -Switch:$false so for your example:

Demo -y:$y

By the way in this example, you could also use splatting:

Demo @PSBoundParameters

But your post is clearly a MVCE so this may not apply to what you're actually doing, or may need modification, especially if you have default values for some parameters (full disclosure: my blog).

briantist
  • 45,546
  • 6
  • 82
  • 127
  • `-switch:$true` is not always redundant. It is possible to make a switch parameter default to $false, in the same way you can give other parameters defaults. – Χpẘ Nov 13 '15 at 02:15
  • @user2460798 that's true but it would be very bad form to do so (in a function definition anyway, in `$PSDefaultParameterValues` it would be fine). It's a good point though so I did edit slightly. – briantist Nov 13 '15 at 02:45