Advanced Functions Part 2: ShouldProcess() in Your Script Cmdlets
Advanced functions' ability to behave almost exactly like a "real" cmdlet isn't limited to parameter binding. You can also take advantage of the common -verbose parameter. Simply output your verbose output this way:
May 17, 2010
Advanced functions' ability to behave almost exactly like a "real" cmdlet isn't limited to parameter binding. You can also take advantage of the common -verbose parameter. Simply output your verbose output this way:
Write-Verbose "Beginning query"
And when the shell's $VerbosePreference variable isn't set to "SilentlyContinue" ("Continue" will enable the output), you'll see your verbose output.
But let's do something cooler. Try this:
Get-Process | Stop-Process -whatif
And now this:
Get-Service | Stop-Service -confirm
(Um, answer "no" when it asks). Stop-Process and Stop-Service both support the -whatif and -confirm parameters, because the cmdlets attempt to modify the system. Any cmdlet - or advanced function - that is going to change something should specify an impact level of either Low, Medium, or High; if the cmdlet is run without the -whatif or -confirm parameters, it will still ask for confirmation if the specified impact level is higher than the shell's built-in $ConfirmPreference variable (which is usually "High"). Your advanced functions can declare their impact level by modifying the CmdletBinding() attribute:
Function Win32Restart-Computer {
[CmdletBinding(
SupportsShouldProcess=$true,
ConfirmImpact="High"