In one of my recent articles for SMB IT, I included a PowerShell module. In the article I referenced that I included support for -Whatif in one of the functions. I was asked on Twitter to explain what I meant and how it works. So here goes.
ManageEngine ADManager Plus - Download Free Trial
Exclusive offer on ADManager Plus for US and UK regions. Claim now!
There are a few ways you can add support for -WhatIf in your PowerShell scripts and functions. The first thing you need to do is add the cmdletbinding attribute at the beginning of your script, before the Param() section, and set SupportsShouldProcess to $True.
[cc lang="PowerShell"]
[cmdletbinding(SupportsShouldProcess=$True)]
[/cc]
In a function you might do this:
[cc lang="PowerShell"]
Function Remove-Data {
<#
comment based help goes here
#>
[cmdletbinding(SupportsShouldProcess=$True)]
Param()
...
[/cc]
Even if you have no parameters, you should still add the Param() statement for this to work properly. Once this is in place, when you run the function it will automatically support -WhatIf. If your function is calling cmdlets that also support -WhatIf, such as Remove-Item, then they will "inherit" the parameter.
[cc lang="PowerShell"]
PS C:\> Remove-Data c:\work\f.txt -whatif
What if: Performing operation "Remove File" on Target "C:\work\f.txt".
[/cc]
In the function referenced in my SMBIT article that is exactly what I am doing. I'm merely passing -WhatIf on to other cmdlets. However, you can also write your own WhatIf handling. You still need the cmdletbinding attribute. But now, when you get to the part of your script where you want to add -WhatIf support you can add code like this:
[cc lang="PowerShell"]
if ($pscmdlet.ShouldProcess($Path)) {
Write-Host "Removing $path" -foregroundcolor Yellow
#my code to do something with $Path goes here
} #shouldprocess
[/cc]
Now when I run my function I get a slightly different output:
[cc lang="DOS"]
PS C:\> remove-data c:\work\f.txt -whatif
What if: Performing operation "Remove-Data" on Target "c:\work\f.txt".
[/cc]
The operation is now the name of my function. This is a useful technique if you want to include WhatIf support using cmdlets that don't support it. I use conditional checks like this to test the flow of my more complicated scripts without actually having them do anything.
As you can see, it is not that difficult and I encourage you to see how you can incorporate these feature into your PowerShell work.
Good article.
This can aslo be helpful:
$pscmdlet.ShouldProcess($path,”Delete”)
There are two other variations of ‘ShouldProcess’