Last active
February 2, 2024 00:09
-
-
Save YoraiLevi/db0a84ff7be60a974f87a527a6ecfe87 to your computer and use it in GitHub Desktop.
Everything you wanted to know about ShouldProcess
This file contains hidden or 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
# https://learn.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-shouldprocess | |
function Test-ShouldProcess { | |
[CmdletBinding( | |
SupportsShouldProcess, | |
ConfirmImpact = 'High' | |
)] | |
param( | |
[Switch]$Force | |
) | |
if ($Force -and -not $Confirm){ | |
$ConfirmPreference = 'None' | |
} | |
echo "`$WhatIfPreference, $WhatIfPreference" # No flag -> False # -Whatif:$false -> False # -Whatif:$true -> True | |
echo "`$ConfirmPreference, $ConfirmPreference" # No flag -> High # -Confirm:$false -> None # -Confirm:$true -> Low | |
$PSCmdlet.ShouldProcess('TARGET') | |
# What if: Performing the operation "FUNCTION_NAME" on target "TARGET". | |
# Confirm | |
# Are you sure you want to perform this action? | |
# Performing the operation "Test-ShouldProcess" on target "TARGET". | |
$PSCmdlet.ShouldProcess('TARGET','OPERATION') | |
# What if: Performing the operation "OPERATION" on target "TARGET". | |
# Confirm | |
# Are you sure you want to perform this action? | |
# Performing the operation "OPERATION" on target "TARGET". | |
$PSCmdlet.ShouldProcess('MESSAGE','TARGET','OPERATION') | |
# What if: MESSAGE | |
# OPERATION | |
# TARGET | |
} | |
function Test-NestedShouldProcess { | |
[CmdletBinding( | |
SupportsShouldProcess, | |
ConfirmImpact = 'High' | |
)] | |
param() | |
echo "Outer `$WhatIfPreference, $WhatIfPreference" # No flag -> False # -Whatif:$false -> False # -Whatif:$true -> True | |
echo "Outer `$ConfirmPreference, $ConfirmPreference" # No flag -> High # -Confirm:$false -> None # -Confirm:$true -> Low | |
if ($PSCmdlet.ShouldProcess('This block','Run nested should process')) { | |
# WhatIfPreference and ConfirmPreference values are inherited and inner function calls will have these values | |
Test-ShouldProcess # No flag prompts # -Confirm:$false doesn't prompt # -Confirm:$true prompts | |
Test-ShouldProcess -Confirm:$false # Never prompts | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment