Powering On and Off VMs in vCenter Using Simple PowerCLI Scripts

Here's a simple VMware PowerCLI script to power on and power off VMs from vCenter:

Prerequisites:

  1. Install VMware PowerCLI on your machine.
  2. Ensure you have the necessary permissions to manage VMs in vCenter.
Power On VM Script:

# Connect to vCenter Server
Connect-VIServer -Server vcenter.example.com -User 'username' -Password 'password'

# Power on a specific VM by its name
$vmName = "VM_Name"
$vm = Get-VM -Name $vmName

# Check if the VM is powered off and power it on
if ($vm.PowerState -eq 'PoweredOff') {
    Start-VM -VM $vm
    Write-Host "$vmName powered on."
} else {
    Write-Host "$vmName is already running."
}

# Disconnect from the vCenter Server
Disconnect-VIServer -Server vcenter.example.com -Confirm:$false

Power Off VM Script:

# Connect to vCenter Server
Connect-VIServer -Server vcenter.example.com -User 'username' -Password 'password'

# Power off a specific VM by its name
$vmName = "VM_Name"
$vm = Get-VM -Name $vmName

# Check if the VM is powered on and power it off
if ($vm.PowerState -eq 'PoweredOn') {
    Stop-VM -VM $vm -Confirm:$false
    Write-Host "$vmName powered off."
} else {
    Write-Host "$vmName is already powered off."
}

# Disconnect from the vCenter Server
Disconnect-VIServer -Server vcenter.example.com -Confirm:$false

Key Points:

  • Replace vcenter.example.com, username, and password with your actual vCenter server details and credentials.
  • Replace "VM_Name" with the VM name you want to manage.
  • The scripts check the current power state of the VM before attempting to power it on or off, preventing unnecessary actions.
  • As always, exercise caution and customise the above to fit your infra requirements.



Comments

Popular posts from this blog

My Journey to Becoming a VMware vExpert: Persistence, Passion & People

Understanding and Customizing ESXi Password Requirements

How do you request an NSX 4.2.1.1 download?