View Only
  • 1.  UPS Shutdown Script - Improvements?

    Posted May 05, 2015 07:25 AM


    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:

    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

  • 2.  RE: UPS Shutdown Script - Improvements?

    Posted May 05, 2015 08:07 AM

    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"}


        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"}


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

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