Are there any official guidelines from Microsoft about when to add -Confirm
, -Force
, and -WhatIf
parameters to custom PowerShell cmdlets? There doesn't seem to be a clear consensus about when/how to use these parameters. For example this issue.
In the absence of formal guidelines, is there a best practice or rule of thumb to use? Here is some more background, with my current (possibly flawed) understanding:
-WhatIf
The -WhatIf
flag displays what the cmdlet would do without actually performing any action. This is useful for a dry run of a potentially destabilizing operation, to see what the actual results would be. The parameter is automatically added if the cmdlet's Cmdlet
attribute has the SupportsShouldProcess
property set to true.
It seems like (but I'd love to see more official guidance here) that you should add -WhatIf
if you are ever adding or removing resources. (e.g. deleing files.) Operations that update existing resources probably wouldn't benefit from it. Right?
-Force
The -Force
switch is 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
parameter means:
Allows the cmdlet to copy items that cannot otherwise be changed, such as copying over a read-only file or alias.
So to me it seems like (again, I'd love some official guidance here) that you should add an optional -Force
parameter when you have a situation where the cmdlet would otherwise fail, but can be convinced to complete the action.
For example, if you are creating a new resource that will clobber an existing one with the same name. The default behavior of the cmdlet would report an error and fail. But if you add -Force
it will continue (and overwrite the existing resource). Right?
-Confirm
The -Confirm
flag gets automatically added like -WhatIf
if the cmdlet has SupportsShouldProcess
set to true. In a cmdlet if you call ShouldProcess
then the user will be prompted to perform the action. And if the -Confirm
flag is added, there will be no prompt. (i.e. the confirmation is added via the cmdlet invocation.)
So -Confirm
should be available whenever a cmdlet has a big impact on the system. Just like -WhatIf
this should be added whenever a resource is added or removed.
With my potentially incorrect understanding in mind, here are some of the questions I'd like a concrete answer to:
- When should it be necessary to add
-WhatIf
/-Confirm
? - When should it be necessary to add
-Force
? - Does it ever make sense to support both
-Confirm
and-Force
?