Are there any official guidelines from Microsoft about when to add -Confirm
, -Force
, and -WhatIf
parameters to custom PowerShell cmdlets?
I haven't researched whether the documentation is this detailed, but the following are based on my observations:
You should use -WhatIf
for anything that makes a change. Updates are changes that can benefit from -WhatIf
(e.g., what if you want to make a lot of updates?).
-Force
means "force overwrite of an existing item" or "override a read-only file system attribute". In either case the success of the action depends on the user having permission.
-Confirm
and -Force
are not mutually exclusive. For example, you can confirm an action to write a file, but the file might be protected with the read-only attribute. In this case the action would fail unless you also specify -Force
.
As an added observation, -Force
should not overrule -WhatIf
. Or in other words: -WhatIf
has priority over -Force
.
If you use:
Get-ChildItem -Recurse | Remove-Item -Recurse -Force -WhatIf
it will result in the following output:
What if: Performing the operation "Remove Directory" on target "E:\some directory\".
It will not actually remove the items, even when -Force
is specified.
This means that you should never write:
if($Force -or $Pscmdlet.ShouldProcess($)) {
...
}
If you want to validate that your implementation of these common parameters is compliant to the guidelines (for example, Set-Xxx cmdlets should have -Confirm and -WhatIf), then you can use the excellent PsScriptAnalyzer
module (which is based on code analysis).
Make sure the module is installed:
PS E:\> Install-Module -Name 'PsScriptAnalyzer'
Then run PowerShell Code Analysis as follows:
PS E:\> Invoke-ScriptAnalyzer -Path . | FL
RuleName : PSUseShouldProcessForStateChangingFunctions
Severity : Warning
Line : 78
Column : 10
Message : Function 'Update-something' has verb that could change system state.
Therefore, the function has to support 'ShouldProcess'.
Documentation (and sources) can be found on GitHub: https://github.com/PowerShell/PSScriptAnalyzer