Are there any official Microsoft recommendations on when to add the -Confirm , -Force and -WhatIf to custom PowerShell cmdlets? There seems to be no clear consensus on when / how to use these parameters. For example, this problem .
In the absence of formal guidelines, is there a best practice or rule of thumb? Here are some more stories, with my current (possibly erroneous) understanding:
-WhatIf
The -WhatIf flag indicates what the cmdlet will do without performing any action. It is useful to dry run a potentially destabilizing operation to see what the actual results will be. The parameter is automatically added if the cmdlet attribute of Cmdlet has the SupportsShouldProcess property set to true.
It seems that (but I would like to see a more formal guide here) that you should add -WhatIf if you ever add or remove resources. (for example, deleting files.) Operations that update existing resources will probably not benefit from this. Correctly?
-Force
The -Force switch -Force used to declare "I know what I'm doing, and I'm sure I want to do this." For example, when copying a file ( Copy-File ), the -Force means:
Allows the cmdlet to copy items that cannot otherwise be changed, such as copying by file or read-only alias.
So it seems to me (again, I would like some official recommendations here) that you should add the optional -Force parameter when you have a situation where the cmdlet otherwise fails, but you can verify the action.
For example, if you create a new resource that will clobber existing with the same name. The default cmdlet behavior will report an error and fail. But if you add -Force , it will continue (and overwrite the existing resource). Correctly?
-Confirm
The -Confirm flag -Confirm automatically added as -WhatIf if the cmdlet has SupportsShouldProcess set to true. In the cmdlet, if you call ShouldProcess , the user will be prompted to perform an action. And if the -Confirm flag is -Confirm , there will be no invitation. (that is, confirmation is added through a call to the cmdlet.)
So, -Confirm should be available whenever the cmdlet has a big impact on the system. Just like -WhatIf , this should be added when adding or removing a resource.
Given my potentially misunderstanding, here are some of the questions I would like to answer in a concrete way:
- When do I need to add
-WhatIf / -Confirm ? - When to add
-Force ? - Does it make sense to support both
-Confirm and -Force ?