Scripting Games Commentary: IV Whatif

PowerShell cmdlets that change the system state have a –whatif parameter to test what would happen for example

PS> Get-Service sp* | Stop-Service -WhatIf
What if: Performing operation "Stop-Service" on Target "Print Spooler (Spooler)".
What if: Performing operation "Stop-Service" on Target "Software Protection (sppsvc)".
What if: Performing operation "Stop-Service" on Target "SPP Notification Service (sppuinotify)".

 

I saw a number of entries where people were creating their own functions to supply whatif parameters. 

STOP.

This is functionality built into advanced functions

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017

function test-whatif {
[CmdletBinding(SupportsShouldProcess=$true)]
param (
 [parameter(ValueFromPipeline=$true,
   ValueFromPipelineByPropertyName=$true)]
 [string]$name
)

PROCESS{
  if ($psCmdlet.ShouldProcess("$name", "Stopping Service")) {
    "Service $name will be stopped"
  }
 
 
}#process

}

 

The important part is [CmdletBinding(SupportsShouldProcess=$true)]   This sets up the use of –whatif.  -Confirm we’ll look at another time

This is the working bit

if ($psCmdlet.ShouldProcess("$name", "Stopping Service")) {
    "Service $name will be stopped"
}

Check to see if  Shouldprocess is called – the parameters are the object the actions is performed on and the action that is being performed respectively (often a cmdlet name) – is it is print the whatif message otherwise perform the normal action

It is used like this

PS> Get-Service sp* | test-whatif
Service Spooler will be stopped
Service sppsvc will be stopped
Service sppuinotify will be stopped

 

No –whatif parameter so we get the action – in this case just a message

if we supply –whatif

PS> Get-Service sp* | test-whatif -WhatIf
What if: Performing operation "Stopping Service" on Target "Spooler".
What if: Performing operation "Stopping Service" on Target "sppsvc".
What if: Performing operation "Stopping Service" on Target "sppuinotify".

We get a What if:….      message

Huge piece of functionality for practically zero code.

Leave a Reply