PowerShell guidelines for -Confirm, -Force, and -WhatIf

后端 未结 3 451
没有蜡笔的小新
没有蜡笔的小新 2021-02-07 16:19

Are there any official guidelines from Microsoft about when to add -Confirm, -Force, and -WhatIf parameters to custom PowerShell cmdlets?

3条回答
  •  不知归路
    2021-02-07 17:07

    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($)) {
        ...
    }
    

提交回复
热议问题