Using PowerCLI to correct vm boot order

Due to how they were installed, I had ~1000 VM’s that were incorrectly left set to a boot order of network first, then hard drive. You can’t correct this by booting into bios, because once a boot order has been set in a way that causes it to end up in the vmx file, the bios boot section is locked out. Not that you’d want to fix a large number of machines in this manner, but even correcting one machine is a pain in the ass doing this way because you have to go into the bios settings while it is down.

Easy way to fix with PowerCLI. First, log into vcenter:

Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Confirm:$false
Connect-VIServer -Server 192.0.2.1 -Protocol https -User admin -Password passCode language: JavaScript (javascript)

Replace VMNAME with your actual vm’s name, then:

$vm = get-vm VMNAME
$disk1 = [VMware.Vim.VirtualMachineBootOptionsBootableDiskDevice]@{
        DeviceKey = (Get-HardDisk -Name 'Hard disk 1' -VM $vm).ExtensionData.Key
}
$bootorder = [VMware.Vim.VirtualMachineConfigSpec]@{
        BootOptions = $vm.ExtensionData.Config.BootOptions
}
$bootorder.BootOptions.BootOrder = $disk1
$vm.extensiondata.ReconfigVM($bootorder)
Code language: PHP (php)

You can check that it worked afterward via:

$vm = Get-VM VMNAME; $vm.ExtensionData.Config.BootOptions | Select BootOrder
Code language: PHP (php)

No need to do anything else; it’s effective next time there’s a reboot of the VM.

If you have a ton of them to check for this, in my case that was easy because a proper VM config will have only one (or zero) specified boot devices, and these problematic VM’s had two (net + hdd). So I wrote a script to run through them and set the boot order if the current number of boot devices is greater than one. The below uses a prefix pattern on the VM names, “pattern*” but you could also just use * to hit every VM if needed.

$vmarray = @(Get-VM -Name pattern* | Select Name)

foreach ($vmName in $vmarray) {
 $vm = Get-VM $vmName.Name;
 if ( ($vm.ExtensionData.Config.BootOptions.BootOrder.Length) -gt 1 ) {
        Write-Host Fixing $vmName.Name `n -NoNewline;
        $disk1 = [VMware.Vim.VirtualMachineBootOptionsBootableDiskDevice]@{
                DeviceKey = (Get-HardDisk -Name 'Hard disk 1' -VM $vm).ExtensionData.Key
        }
        $bootorder = [VMware.Vim.VirtualMachineConfigSpec]@{
                BootOptions = $vm.ExtensionData.Config.BootOptions
        }
        $bootorder.BootOptions.BootOrder = $disk1
        $vm.extensiondata.ReconfigVM($bootorder)
 }
}
Code language: PHP (php)

Leave a Reply

Your email address will not be published. Required fields are marked *