Automate VM Power State Management in VMware vSphere with PowerShell
PowerShell scripts can significantly streamline your workflows in VMware vSphere by automating common tasks such as managing the power state of your virtual machines (VMs). The following script showcases how to retrieve the power state of all VMs in your vSphere environment and allows you to power on or off specific VMs based on their names. This script is perfect for system administrators looking to optimize their management tasks. Ensure you have the necessary PowerCLI module installed and connected to your vSphere server before executing the script.
# Load the VMware PowerCLI module
Import-Module VMware.PowerCLI
# Connect to the vSphere server
$vcServer = vcenter.domain.com
$vcUsername = username
$vcPassword = password # Ensure to use a secure method to store passwords
$securePassword = ConvertTo-SecureString $vcPassword -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($vcUsername, $securePassword)
Connect-VIServer -Server $vcServer -Credential $cred
# Get the power state of all VMs
$allVMs = Get-VM
$allVMs | Select-Object Name, PowerState
# Powering off a specific VM
$vmName = YourVMName
$vm = Get-VM -Name $vmName
if ($vm.PowerState -eq PoweredOn) {
Stop-VM -VM $vm -Confirm:$false
Write-Host "Successfully powered off $vmName"
} else {
Start-VM -VM $vm -Confirm:$false
Write-Host "Successfully powered on $vmName"
}
# Disconnect from the vSphere 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.