PowerShell Scripting -WhatIf and -ConfirmIntroduction to PowerShell Scripting -WhatIf and -ConfirmWhatIf and confirm are two great commands for testing complicated scripts without risking the code running amok. For example, if you decide to delete files by using a script containing wildcards, there could be all manner of unexpected side effects. By employing PowerShell, and appending -whatIf you get a preview of would happen without risking any damage. WhatIf Topics
Mission to delete filesLet us take a real life example, we wish to delete files, but because we are using wildcards we are concerned about deleting the wrong type of file. Instead of gung-ho Guy deleting the files - ready or not, we will take the cautious approach and append -whatIf. The result is PowerShell completes the command and shows us the result, but does not delete any files. Incidentally, I cannot find a delete verb in PowerShell, there is however, a remove verb. -whatIf exampleBy adding -whatIf at the end of the command we are saying to PowerShell: 'Just test, don't actually make any permanent changes'. Please note, there could be serious consequences if you don't use the -whatIf switch. If you don't understand what you are doing, you could delete all your .txt files. # PowerShell script featuring -whatIf A breakdown of what the above script achieves get-Childitem (Rather like dir) -confirm exampleHere is another parameter that you append to a 'normal' script - confirm. It really is a case of confirm by name, and confirm by nature. PowerShell says to you: 'Do you really want to do this?' # PowerShell script featuring -confirm The result of -confirm is that PowerShell presents you with choices, however, remember this is now 'live' therefore if you press [Y] or [A] then files will be deleted. [Y] Yes [A] Yes to all [N] No [L] No to all [S] Suspend Summary of -whatIf and -confirm in PowerShellOnce you have used -whatIf and -confirm you will think, 'Why don't all scripting languages have these safety features'.
˚
See also PowerShell syntax• PowerShell Home • Syntax • Loops • Variables • What If • Functions • Replace Please write in if you see errors of any kind. Please report any factual mistakes, grammatical errors or broken links, I will be happy to not only to correct the fault, but also to give you credit.
*
|
||||||