Powering On and Off multiple Virtual Machines Using PowerCLI

powercli

There may come a time where you need to power on or off a bunch of virtual machines.  Instead of having to do them one by one you can use PowerCLI to do exactly that. I sometimes use PowerCLI and other times use PowerGUI Script Editor.  Below is the code to Power ON multiple VM’s.

You will need to specify a text file that contains a list of your servers that you would like powered on

<pre>
# Start Load VMware Snapin (if not already loaded)
if (!(Get-PSSnapin -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue)) {
if (!(Add-PSSnapin -PassThru VMware.VimAutomation.Core)) {
# Error out if loading fails
Write-Error "ERROR: Cannot load the VMware Snapin. Is the PowerCLI installed?"
Exit
}
}
# End Load VMware Snapin (if not already loaded)

# Global Paramenters
$VIServer = "vcentername"

#Username and Password are optional you just have to remove the global parameters and where is calls for the Parameters
$Username = "username"
$Password = "password"
$servers= Get-Content c:\scripts\servers.txt
$OpenConnection = $global:DefaultVIServers | where { $_.Name -eq $VIServer }
if($OpenConnection.IsConnected) {
Write-Output "vCenter is Already Connected..."
$VIConnection = $OpenConnection
} else {
Connect-VIServer -Server $VIServer -User $Username -Password $Password
}

Start-VM -VM $servers -RunAsync

Disconnect-VIServer $VIServer -Confirm:$false

 

Now to power off your servers its a simple script as well. You will use a text file that contains your servers you wish to power off. This will do a graceful-shutdown of your VM’s

# Start Load VMware Snapin (if not already loaded)
if (!(Get-PSSnapin -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue)) {
 if (!(Add-PSSnapin -PassThru VMware.VimAutomation.Core)) {
 # Error out if loading fails
 Write-Error "ERROR: Cannot load the VMware Snapin. Is the PowerCLI installed?"
 Exit
 }
}
# End Load VMware Snapin (if not already loaded)

# Global Paramenters
$VIServer = "vcentername"

</pre>
<pre>#Username and Password are optional you just have to remove the global parameters and where is calls for the Parameters$Username = "Username"
$Password = "Password"
$servers= Get-Content c:\scripts\servers.txt


$OpenConnection = $global:DefaultVIServers | where { $_.Name -eq $VIServer }
if($OpenConnection.IsConnected) {
 Write-Output "vCenter is Already Connected..."
 $VIConnection = $OpenConnection
} else {
Connect-VIServer -Server $VIServer -User $Username -Password $Password
}

Get-vm $servers | Shutdown-VMGuest

Disconnect-VIServer $VIServer -Confirm:$false

No comments.

Leave a Reply