Ezine 157 PowerShell’s -whatIf…
-whatIf is not a magic bullet, but it is PowerShell’s magic shield.
When you create a PowerShell script, and you sense that the commands are moving out of your comfort zone, simply add the -whatIf switch. This appendage allows your script to execute as normal, it even models the results, but the -whatIf parameter prevents the code from actually taking any action. When the output matches your expectation, then simply remove the -whatIf and run the script again; the code will now carry out your intended action. This is how -whatIf becomes a magic shield for your PowerShell scripts.
PowerShell Topics for PowerShell’s -whatIf
- This Week’s Secret
- This Week’s Mission
- Two Preliminary Steps
- Example whatIf script to delete temporary files from a named folder
- More -whatIf examples
With VBScript, I shied away from publishing scripts which deleted objects. My reasoning was this, the law of averages dictates that at least one reader would get the wrong end of the stick, and as a result they would delete their entire D:\ drive, or an entire branch of their active directory tree.
I can take criticism of my zany ideas on the chin, but a reader’s letter saying that my VBScript destroyed their machine, I take to the heart. Even if the reader disregarded my instructions, and failed to take reasonable precautions, I feel some responsibility. With PowerShell I have no such guilty feeling because we have the -whatIf command to shield us from silly errors.
This Week’s Mission is to delete temporary files, but before our script kills the files we are going to check their names. Any time we use wildcards, there is well-founded concern that we could delete the wrong files. The best way to lift this cloud of worry is to append -whatIf. The result is PowerShell completes the command, and while it shows us the result, PowerShell does not delete any files. If the result is what you anticipated, simply remove the -whatIf.
Note: In PowerShell there is no such verb as ‘delete’, however, there is verb called ‘remove’. If you research with: get-Command remove*, then you will discover a whole family of ‘remove’ verbs, for example, remove-Item and remove-ItemProperty. Moreover, if you have extra QAD cmdlets, they too also use the verb ‘remove’ and not delete, e.g. remove-QADGroupMember.
The practical details of our mission
What I want to do is to create a script which will delete your temporary files. Before we start I would like to highlight the two most important variables in our mission, firstly the location of such tmp files, and secondly the file type or file extension.
Regarding the question of location, here are two paths that we could use, C: \Windows\Temp or C: \Documents and Settings
Guy Recommends: The Free IP Address Tracker (IPAT)
Calculating IP Address ranges is a black art, which many network managers solve by creating custom Excel spreadsheets. IPAT cracks this problem of allocating IP addresses in networks in two ways:
For Mr Organized there is a nifty subnet calculator, you enter the network address and the subnet mask, then IPAT works out the usable addresses and their ranges.
For Mr Lazy IPAT discovers and then displays the IP addresses of existing computers. Download the Free IP Address Tracker
Preliminary Script 1. For the sake of safety, and for learning progression, let us start with a script which merely lists the files in the folder specified by $Location. To be clear, we are not appending the -whatIf parameter just yet. Apart from familiarising yourself with my $Location variable, the idea of this script is to introduce get-Childitem which is like the ‘dir’ command.
# PowerShell script to list files
Note 1: If this location does not produce any results, try a different folder.
Note 2: If you still don’t get any results add the -recurse parameter, AND switch to the plain root folder, C: \Windows
Preliminary Script 2. Let us add two parameters: -include, which filters the file extension, and -recurse which loops through the files and seek out any sub-directories.
# PowerShell script to list .tmp files
get-ChildItem $Location -include *.tmp -recurse
Note 3: If you don’t get any results, substitute *.log for *.tmp. Or even revert to the famous *.*.
Note 4: If you still don’t get any files, then try a different location, see notes 1-3 above.
Following the above preliminary scripts, we are now ready to employ an important PowerShell technique, namely piping. The idea is that the output of the first part, becomes the input for the remove-Item command. The piping command is controlled by the vertical bar ‘|’. On my keyboard, it’s down by the ‘Z’. Furthermore, because remove-Item could delete the wrong files, here is where we add the -whatIf.
# PowerShell script featuring -whatIf
$Location = "C:\windows\temp"
get-ChildItem $Location -include *.tmp -recurse | remove-Item -whatif
Expected result: Performing operation "Remove File" on Target :
To convert the above code into a production script, just remove the -whatIf parameter. Optionally create a cmdlet file containing those three lines and a .ps1 extension.
A breakdown of the commands in the above script.
get-Childitem (Rather like dir)
C:\windows\temp (Location to start)
-include *.tmp (The pattern to look for)
-recurse (Search subdirectories)
| Pipes the output of the first half into
remove-Item (The equivalent of Delete)
-whatIf Says: PowerShell, please test, but don’t actually complete the operation. In this example, simply show me which files with a .tmp extension would be deleted if I removed the -whatIf.
Tired of writing scripts? The User Management Resource Administrator solution by Tools4ever offers an alternative to time-consuming manual processes.
It features 100% auto provisioning, Helpdesk Delegation, Connectors to more than 130 systems/applications, Workflow Management, Self Service and many other benefits. Click on the link for more information onUMRA.
Summary of PowerShell’s -whatIf
While I chose deleting files as a classic example of using -whatIf, my greatest joy would be if you found other scenarios for this parameter. Once you have mastered -whatIf you think, ‘Why don’t all scripting languages have this safety shield?’