This post provides a useful PowerShell script for managing virtual machines in VMware vSphere. You will learn to automate the processes of powering on and off VMs based on specific criteria. This automation helps IT administrators save time and ensure efficient VM management.
powershell
# Define vCenter Server connection details
$vcServer = "vcenter_server_IP_or_FQDN"
$vcUser = "username"
$vcPassword = "password"
# Connect to the vCenter Server
Connect-VIServer -Server $vcServer -User $vcUser -Password $vcPassword
# Specify the VM name
$vmName = "Your_VM_Name"
# Get the VM object
$vm = Get-VM -Name $vmName
# Check if the VM is powered off; power it on if necessary
if ($vm.PowerState -eq PoweredOff) {
Start-VM -VM $vm
Write-Host "$($vm.Name) has been powered on."
} else {
Write-Host "$($vm.Name) is already powered on."
}
# Check if the VM is powered on; power it off if necessary
if ($vm.PowerState -eq PoweredOn) {
Stop-VM -VM $vm -Confirm:$false
Write-Host "$($vm.Name) has been powered off."
} else {
Write-Host "$($vm.Name) is already powered off."
}
# Disconnect from the vCenter Server
Disconnect-VIServer -Server $vcServer -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.