$PSBoundParameters and CommonParameters (-WhatIf, -Debug, etc.)

For the longest time, I was unable to get $PSBoundParameters to work to detect –Debug, -Verbose, etc. CommonParameters. Here’s a handy page that captures the output of about_CommonParameters.

https://technet.microsoft.com/en-us/library/hh847884.aspx

There are two dependencies:

[CmdletBinding()] – This must be the first line of the script, above even the previous "this must be the first line of the script," param().

param() – Even if your script only takes the CommonParameters and nothing more, you have to have a param() statement, otherwise [CmdletBinding()] doesn’t work.

Once that’s satisfied, you can test for the presence of CommonParameter flags like this:

if ($PSBoundParameters['Verbose']) { ... }

You can also pass on the values to cmdlets and other functions the current function or script calls:

-Verbose:([bool]($PSBoundParameters[‘Verbose’]))

However, whatever special handling you do is on your own. This is why I’m not likely to support –WhatIf in my scripts anytime soon.