← script library

Automating VM Power Management in VMware vSphere with PowerShell

VMware & vSphereJanuary 6, 2025

Managing virtual machines (VMs) in VMware vSphere can be tedious without automation. This PowerShell script allows you to start, stop, or restart VMs based on their names. By using this script, you can save time and streamline your workflow.

powershell
# Load VMware PowerCLI module
Import-Module VMware.PowerCLI

# Connect to vSphere server
$vCenterServer = "your_vcenter_server"
$username = "your_username"
$password = "your_password"
Connect-VIServer -Server $vCenterServer -User $username -Password $password

# Define VM names and action
$vmNames = @("VM1", "VM2", "VM3") # Replace with your VM names
$action = "Start" # Options: Start, Stop, Restart

# Perform the action on each VM
foreach ($vmName in $vmNames) {
    $vm = Get-VM -Name $vmName
    if ($null -ne $vm) {
        switch ($action) {
            "Start" { Start-VM -VM $vm }
            "Stop" { Stop-VM -VM $vm }
            "Restart" { Restart-VM -VM $vm }
            default { Write-Host "Invalid action specified." }
        }
        Write-Host "$action action performed on $vmName."
    } else {
        Write-Host "VM $vmName not found."
    }
}

# Disconnect from vSphere
Disconnect-VIServer -Server $vCenterServer -Confirm:$false

Run 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.

Ready when you are.

Try ServerEngine free for 7 days.