What if / Wat als [Powershell]


One of the best (little known?) features about Powershell is the -WhatIf switch. A script or cmdlet can have parameters, of course, like

param( [string] $foo )

but it can also have switches that are on or off like

param ( [switch] $verbose )

One of the mostly ubiquitous switches is -WhatIf for commands that could “do damage.” For example:

PS> del foo.txt -whatif
What if: Performing operation “Remove File” on Target “C:\foo.txt”.
PS> get-process outlook | stop-process -WhatIf
What if: Performing operation “Stop-Process” on Target “OUTLOOK (2540)”.

Drink in how useful this can be. Fabulous. Anyway, so we wanted to make our own scripts have this ability. Since our scripts are mostly strung together with built-in commands, we want to have a WhatIf switch be inherited by the sub-commands.

Switches are either present or not present so I tried a silly thing like this:

param ( [string] $file, [switch] $WhatIf)
if ($WhatIf.IsPresent) { $WhatIf = “-WhatIf” }
del $file $WhatIf

But this is cleaner:

“You can forward switch params to cmdlet parameters of type switch like so”

param([string]$file, [switch]$WhatIf=$false)
del $file -WhatIf:$whatif



Shoutout to PoshGUI

I came across very cool website for Microsoft Powershell, it is free powershell GUI designer tool online. Powershell lovers who like to create graphical interface will definitely like this website, if they want to create a GUI structure and put there code for automation, Its very easy one and helpful excellent tool online, it in beta version but worth trying . You can signup on the website, to Save or Load Form. on the left side there are few necessary controls, click on any of one and then click on form, it will be loaded visible on form, and Right had side control properties can be modified. If you want to delete the control select it and there is Delete control button on the top.

Most important part is in the bottom once GUI form is created, Copy the code in your favorite PowerShell editor tool, modify it add your code and execute it. I am hoping near future more form controls will be added on the web site. below is the website url link, Share your feedback.



Try fiddling with it and see the usage of this wonderfull script.