Tuesday, October 18, 2011

Switch/Flag Parameters in PowerShell

I wanted to create a function with a ‘-force’ option.  First, I tried to add a [boolean] parameter, but that doesn’t work because it needs a value with the argument; I want it to be invoked with just the presence of the switch/flag.  Here’s how I finally did it:

function Update-Something {
param(
[switch] $force)

if ($force) {
#do something here
}
}


# use like:
$> Update-Something -force

4 comments:

  1. Thanks for this one. I have been looking for how to do this forever. I think my problem was vernacular. I was looking for 'switch' instead of 'flag'. Anyway, a short post but a useful one!

    ReplyDelete
  2. Glad you found it! Maybe I should start updating this blog again...

    ReplyDelete
  3. Thanks, needed that. Used it here: http://echohellowordl.blogspot.com/2016/01/powershell-logging-function.html

    ReplyDelete