PowerShell Script for Bulk VM Power Management in VMware vSphere

In this post, Ill share a PowerShell script that simplifies the process of managing multiple virtual machines (VMs) in VMware vSphere. This script allows you to bulk start, stop, or restart VMs, making it a handy tool for IT professionals managing vSphere environments. With just a few commands, you can manipulate the power state of your VMs efficiently.
Ensure you have VMware PowerCLI installed and your environment set up correctly before running the script. Lets walk through the steps of the script:
### Step 1: Install VMware PowerCLI
First, make sure you have the VMware PowerCLI module installed, which is essential for interacting with vSphere.
“`powershell
# Install VMware PowerCLI module
Install-Module -Name VMware.PowerCLI -AllowClobber -Force
“`
### Step 2: Connect to vSphere Server
Initiate a connection to your vSphere server. Youll need to supply the vCenter server address and your credentials.
“`powershell
# Connect to vSphere server
$server = “your_vcenter_server”
$username = “username”
$password = “password”
Connect-VIServer -Server $server -User $username -Password $password
“`
### Step 3: Get a List of VMs
This step retrieves the virtual machines you wish to manage. You can customize the retrieval based on your requirements, e.g., filtering by name or tags.
“`powershell
# Get a list of all VMs
$vmList = Get-VM
“`
### Step 4: Define a Power Action
This part of the script allows you to define what action you want to take on the VMs. The options include “Start”, “Stop”, or “Restart”.
“`powershell
# Define the power action
$action = “Start” # Change this to “Stop” or “Restart” as needed
“`
### Step 5: Execute the Power Action
Now you can loop through the list of VMs and perform the defined action. The script handles each VM accordingly.
“`powershell
# Execute the defined power action
foreach ($vm in $vmList) {
switch ($action) {
“Start” {
Start-VM -VM $vm
Write-Host “Started VM: $($vm.Name)”
}
“Stop” {
Stop-VM -VM $vm -Confirm:$false
Write-Host “Stopped VM: $($vm.Name)”
}
“Restart” {
Restart-VM -VM $vm -Confirm:$false
Write-Host “Restarted VM: $($vm.Name)”
}
}
}
“`
### Step 6: Disconnect from vSphere
Finally, disconnect from the vSphere server to ensure that you close the session properly.
“`powershell
# Disconnect from vSphere server
Disconnect-VIServer -Server $server -Confirm:$false
“`
This PowerShell script efficiently manages the power state of your VMs in VMware vSphere, making your workflow more streamlined.
For more powerful tools and scripts tailored for server management, consider exploring my software, ServerEngine, available at [https://serverengine.co](https://serverengine.co).