# Tahir Hassan's Blog

My Technical Notes

## Saturday, 21 January 2017

### PowerShell: Overriding ConfirmPreference

In PowerShell, if you define a function which SupportsShouldProcess and you call it with -Confirm switch, it will run the function with $ConfirmPreference set to Low. Therefore those commands which even have a Medium impact (ConfirmImpact), such as Move-Item will ask for confirmation. To prevent this, we can call such functions with -Confirm set to $false:


Move-Item -Path .\Foo.txt -Destination .\Bar.txt -Confirm:$false  Another method of doing this, is to set the $ConfirmPreference to High (which is the default), and isolate its effects from the rest of the function by using the call operator (&) on a script block:


& {
$ConfirmPreference = 'High'; Move-Item -Path .\Foo.txt -Destination .\Bar.txt }  The second approach is well-suited to situations in which we have many function calls for which we want to disable confirmation. However, it does not work for calls to $PSCmdlet.ShouldProcess.

Another approach which works in all scenarios, but is syntactically heavy, is by creating a scriptblock with a CmdletBinding attribute, setting SupportsShouldProcess to true so we can then pass in Confirm as false:


& {
[CmdletBinding(SupportsShouldProcess=$true)] param() Move-Item -Path .\Foo.txt -Destination .\Bar.txt } -Confirm:$false;