You never know, your VMware vSphere ESXi host may break, hardware may fail or something else forces you to restore your configuration to a new server. Whatever the reason is, it’s always good to have a backup laying around to be able to restore quickly from a disaster. This backup script takes a backup of the VMware Host configuration (not the VMs itself) and is very useful if you want to restore a Host to a new server.

This script is run on a computer with Windows 10 installed on the local network (don’t forget to allow the computer to access the server in the firewall), but could also be run on a remote computer, not tested that yet though.

To be able to run this script you need to install PowerCLI. We run version 6.5 at the moment. You also need to move the `Initialize-PowerCLIEnvironment.ps1` to the backup folder, as for some strange reason Powershell can’t read paths with spaces. You can find that script in `C:\Program Files (x86)\VMware\Infrastructure\PowerCLI\Scripts` after you installed PowerCLI.

Then just open Powershell as administrator and run:

PS C:\WINDOWS\system32> Set-ExecutionPolicy RemoteSigned
PS C:\WINDOWS\system32> notepad.exe C:\Users\[user]\Nextcloud\ESXi_Backup\ESXi_Backup.ps1

and add this script:

# Variables
$Server = "[IP or Hostname]"
$Folder = “C:\Users\[user]\Nextcloud\ESXi_Backup”
$FolderOld = “$Folder\Old”
$Date = Get-Date -f "dd-MM-yyyy"
$DateOld = "{0:dd-MM-yyyy}" -f (get-date).AddDays(-30)
$Pass = "SecretPassword"

# Load PowerCLI
Invoke-Expression $Folder\Initialize-PowerCLIEnvironment.ps1
Start-Sleep 3
Add-PSSnapin VMware.VimAutomation.Core -ErrorAction SilentlyContinue

# Connect to local ESXi Server
Connect-VIServer $Server -Username root -Password $Pass -Verbose


# Move existing backup files to the old directory
Get-ChildItem -Path "$Folder\*.tgz" -Recurse | Move-Item -Force -Destination "$FolderOld\"

# Backup ESXi configuration
Get-VMHost | get-vmhostfirmware -BackupConfiguration -DestinationPath $Folder
Rename-Item -Force $Folder\configBundle-$Server.tgz -newName $Folder\$Date--$Server.tgz

# Delete old backup
If (Test-Path $FolderOld\$DateOld--$Server.tgz){
    Remove-Item $FolderOld\$DateOld--$Server.tgz
}

# Disconnect session vCenter 
Disconnect-VIserver -Server $Server -Confirm:$false

We make the backup to our local Nextcloud folder, but you can choose whatever folder or path that suits you of course.

schedule the task in windows

To run this as a scheduled task in Windows, you have to open the Task Scheduler and add a new job that is run with the highest privileges and add a new task like this. Then add this line to be run:

powershell -WindowStyle Hidden -file "C:\Users\[user]\Nextcloud\ESXi_Backup\ESXi_Backup.ps1"

And you’re all set!