← script library
Automating Virtual Machine Power Management in VMware vSphere
VMware & vSphereJanuary 6, 2025
Today, we present a script that helps you to start or stop virtual machines based on their current power state. This can be particularly useful in scheduling tasks and optimizing resource usage.
powershell
# Install the VMware PowerCLI module if not already installed
Install-Module -Name VMware.PowerCLI -Scope CurrentUser -Force
# Connect to the vSphere server
$server = "your_vcenter_server"
$username = "your_username"
$password = "your_password"
Connect-VIServer -Server $server -User $username -Password $password
# Start or stop virtual machines based on their current state
$vms = Get-VM
foreach ($vm in $vms) {
if ($vm.PowerState -eq "PoweredOff") {
# Start the VM
Start-VM -VM $vm
Write-Host "$($vm.Name) has been started."
} elseif ($vm.PowerState -eq "PoweredOn") {
# Stop the VM
Stop-VM -VM $vm -Confirm:$false
Write-Host "$($vm.Name) has been stopped."
}
}
# Disconnect from vSphere server
Disconnect-VIServer -Server $server -Confirm:$falseRun it across your fleet
This script runs as-is on a single host. Paste it into ServerEngine to schedule it, run it on a whole server group in parallel, and keep the credentials out of the file — see the scripts documentation and the credential store.
More in VMware & vSphere
Ready when you are.
Try ServerEngine free for 7 days.