Last active
November 15, 2024 13:30
-
-
Save refactorsaurusrex/90768d5d5a82d9249a747e1169db59d5 to your computer and use it in GitHub Desktop.
PowerShell: What's the difference between ShouldContinue and ShouldProcess?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# The default is High. Setting it here for clarity. | |
# https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_preference_variables?view=powershell-5.1 | |
$ConfirmPreference = 'High' | |
[CmdletBinding(SupportsShouldProcess=$true)] | |
param( | |
[switch]$Force | |
) | |
# Use this to prompt the user by default. Use the -Force parameter to disable prompting. | |
# NOTE: You have to include a $Force parameter yourself, as shown above. It doesn't have to be | |
# named '$Force'. You can name it whatever you want, but 'Force' seems like the most common verb. | |
if ($Force -or $PSCmdlet.ShouldContinue("Some resource", "Would you like to continue?") ) { | |
Write-Host "If you're reading this, you either passed in `$Force` or typed 'Y' when prompted." -ForegroundColor Red | |
} | |
# Use this to NOT prompt by default. Use -Confirm to enable prompting. Or, use the -WhatIf option to | |
# print to console the anticipated outcome of running this block, without actually running it. | |
# NOTE: Both -Confirm and -Whatif are common PS parameters. You don't need to implemented them like $Force was above. | |
if ($PSCmdlet.ShouldProcess("Some other resource", "Would you like to process?") ) { | |
Write-Host 'This will always run UNLESS the -Confirm or -Whatif option is used.' -ForegroundColor Red | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very succinct - this should be the example in the official docs.