Categories

Yes I’m sure

One of the great safety features of PowerShell are the –whatif and –confirm parameters on cmdlets. They can really be useful in preventing hideous, career limiting actions

 

We can create the same functionality on our advanced functions

function test-whatifconfirm {             
[CmdletBinding(SupportsShouldProcess=$true,             
    ConfirmImpact="High")]             
param (             
   [string]$computer="."             
)             
BEGIN{}#begin             
PROCESS{            
            
## Whatif code            
if ($psCmdlet.ShouldProcess("$computer", "get-process on")) {            
   get-process            
}            
            
}#process             
END{}#end            
            
}


put the cmdletbinding attribute into the function



 



[CmdletBinding(SupportsShouldProcess=$true,
    ConfirmImpact="High")]



 



if you want to use ConfirmImpact you need ShouldProcess=$true



 



We then need a bit of code to perform the tests



 



if ($psCmdlet.ShouldProcess("$computer", "get-process on")) {
   get-process
}



 



In this case if –whatif isn’t used get-process runs as this test shows



 



test-whatifconfirm                                                                                                                      



get-process runs



 



if we use –whatif then a message is printed – notice that the two parameters for ShouldProcess are in the order of object and message



 



test-whatifconfirm –WhatIf  



see message



What if: Performing operation "get-process on" on Target ".".



 



The ConfirmImpact attribute can be set to None, Low, Medium or High. Its usage depends on the value of $confirmpreference



The default for $confirmpreference is High



 



test-whatifconfirm –Confirm



will show the confirmation dialog



 



The ConfirmImpact attribute needs to be set equal to or higher than the value of $confirmpreference



 



Two great bits of functionality for minimal effort

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>