Contributor
Contributor

UPS Shutdown Script - Improvements?

Hi

This week I wrote a small script which gets triggered from an UPS in case of power outages. Its task is to shut down the virtual machines and then the ESXi hosts after. Since I'm basicly new to PowerShell im asking for any improvements to the script you could think of. I'm especially concerned about the runtime efficiency of the script. The script has around 20min to shut down almost 500 virtual machines.. so im trying to use as less loops etc. as possible.

Here is the script:

3_shutdown_english.PNG

I've also attached a .zip with the .ps1 and .png for better viewing. Now please bare in mind.. im a PowerShell beginner.

In general there is one method doing the work. I've associated every virtual machine with a Tag of a certain priority level. Hence P1 gets shut down before P2 and so on. Another script assigns all the Tags. The method basicly gets the name of the priority level and checks for vms with working tools to shut down gracefully and then those wich have to be killed. I'll have to enter the sequence manually towards the bottom. But that should be a one time thing. For new virtuall machines I'll stick to configuring Tags.

Looking forward to suggestions.

Regards, David

0 Kudos
1 Reply
Leadership
Leadership

You could optimise the shutdownVM function like this.

Only one Get-VM and Shutdown-VMGuest and Stop-VM on multiple VMs in 1 call.

function shutdownVM($prioTag)

{

  $vms = Get-VM -Tag $prioTag

 

  $graceful = $vms | where {$_.ExtensionData.Guest.ToolsStatus -eq "toolsOk"}

  if($graceful){

    Write-Host "Shutting down $($graceful.Count) vms!"

    Shutdown-VMGuest -VM $graceful -Confirm:$false | Out-Null

  }

 

  $hard = $vms | where {$_.PowerState -eq "poweredon"} | where {$_.ExtensionData.Guest.ToolsStatus -ne "toolsOk"}

  if($hard){

    Write-Host "Tools not responding. Killing $($hard.Count) vms!"

    Stop-VM -VM $hard -Kill -RunAsync -Confirm:$false | Out-Null

  }

}


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos