Should I Stay or Should I Process Now?
One of my goals for this newsletter is to help you write better PowerShell scripts. More than that, I want to provide the information you need to create professional-grade and enterprise-ready PowerShell tools. Just about anyone can throw together a PowerShell script or simple function that gets the job done. But I want you to be creating tools at the next level. Part of this process is learning what questions to ask and how to think about your code. The other part is pure mechanics; what code do I write to get the desired result?
Today I want to share my thoughts on a topic that I don’t think enough PowerShell scripters pay attention to. I’m sure that most of my readers can write a PowerShell function to do something like configure a service or create a user account. But there is more to the process than actually doing it. Any code that alters the state of the environment should support -Whatif
and -Confirm
.
If your PowerShell code creates, changes, or removes something, it should be able to be executed, showing what it would have done. You see this behavior in native PowerShell commands.
PS C:\> Get-Service spooler,bits,winrm | Restart-Service -WhatIf
What if: Performing the operation "Restart-Service" on target "Background Intelligent Transfer Service (bits)".
What if: Performing the operation "Restart-Service" on target "Print Spooler (spooler)".
What if: Performing the operation "Restart-Service" on target "Windows Remote Management (WS-Management) (winrm)".