Thursday, 2 June 2016

How to reboot multiple Virtual Machines on an ESXi host

Recently I got a request to schedule the reboot of multiple VMs on an ESXi host on every weekend.

Let me explain the scenario first. 

1. We need to schedule the reboot of all 50 VMs on every Saturday at 10.00PM (all those machines are Windows servers)

2. Both ESXi and vCenter are version 5.5

3. PowerCLI is installed on vCenter server.

Step-by-step Instructions

1. RDP to your vCenter server (if you are using vCenter server appliance you need to make changes on the below steps accordingly)

2. Make sure that you have enabled access for your domain user (domain administrator)\local server administrator so that they can access vCenter. If you haven't done this please follow

3. Open a notepad and copy paste the below script, save the file as 'VMReboot.ps1'

    [parameter(Mandatory = $true)]
    [parameter(Mandatory = $true)]

$VIServer = Connect-VIServer $vCenter
If ($VIServer.IsConnected -ne $true){
    Write-Host "error connecting to $vCenter" -ForegroundColor Red

foreach($vm in $vmName){
        Write-Host "Going to restart $vm"
        Restart-VMGuest -VM (Get-VM $vm) -Confirm:$false

Disconnect-VIServer -Confirm:$false

4. Open PowerShell and test the script first (see below screenshot).

You need to mention your vCenter server and name of VMs you need to reboot. If you have multiple VMs separate the names with comma or if all VMs start with a common prefix use wild card (eg. "TestVM*")

See the VMs you have mentioned are getting rebooted. If the script works then schedule this job using Windows Task Scheduler

5. Open Task Scheduler and Create a basic task 

6. Mention your schedule and on Actions > Start a Program

Program/script : C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe

Add arguments-PSConsoleFile "C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\vim.psc1" " &  "C:\VMReboot.ps1" -vCenter VCENTER-SRV -vmName "TestVM*"

Verify if the scheduled task is working by running it.

Enable Task History to make sure that the scheduled task is working properly

All the best!