Leveraging -WhatIf command in PowerShell & PowerCLI Scripts

Posted by

Have you ever been writing a PowerShell or PowerCLI script and wished you could see what would happen if you executed the script just to confirm everything is working properly? Have you ever been been performing single commands that modify the environment and you want to ensure the mod you want is the one applied? I am sure many of you are familiar with the -WhatIf command but for those of you who need a refresher I thought I would write this article.

If you would like assistance in the below or have general questions about Cloud solutions, VMware, and more, feel free to visit the following URL and I will be able to work directly with you:
https://bit.ly/3qcNxsN

What is WhatIf:
Indicates that the cmdlet is run only to display the changes that would be made and actually no objects are modified.

I know what you are thinking, that was a basic definition but what more do you need for a simple if you do A then it will either work and get A result or it won’t work and you get an error. Now if you do A and get A+B result and you don’t want B, then you can go figure out how B got added in and remove it.

Example script – Let’s say I have a .csv file with a list of VMs that I want to power off. I want to ensure A. the script will work & B. that only thedesired VMs will be powered off.
As you can see with my script below it will either work or it won’t. You’re hoping that the list of VMs to power off in the .csv is correct.

#vcenter name or IP
$vcenter = “vCenter”
#Path to csv file
$path = “E:\Data\Scripts\listofvms.csv”

connect-viserver $vcenter
$vmlist = import-csv $path | select -ExpandProperty NAME
foreach ($vm in $vmlist) {
Get-VM $vm | Where-Object {$_.powerstate -eq ‘PoweredOn’} | Shutdown-vmguest -Confirm:$false}
Disconnect-VIServer -confirm:$false

As long as you made sure all the VMs in your csv file were accurate you would have no worries right? Would it hurt to double check real quick?
Script with -WhatIf

#vcenter name or IP
$vcenter = “vCenter”
#Path to csv file
$path = “E:\Data\Scripts\listofvms.csv”

connect-viserver $vcenter
$vmlist = import-csv $path | select -ExpandProperty NAME
foreach ($vm in $vmlist) {
Get-VM $vm | Where-Object {$_.powerstate -eq ‘PoweredOn’} | Shutdown-vmguest -Confirm:$false}
Disconnect-VIServer -confirm:$false -WhatIf

Result:
The script with -WhatIf will now run through the list of VMs tell you which VMs it will power down should you execute the script as planned. This allows you to confirm only the desired VMs are going to be powered down but also confirms your script will work.

Summary:
As you can see I am a fan of the WhatIf command. I use it to test all my scripts prior to executing the actual script. As always, I hope y’all found this article useful.

Leave a Reply