Monday, December 8, 2014

Power CLI script to take snapshots from a list of VMs.

The text file needs to contain a list of VMs 1 per row.


This script will perform several functions. First it will shut the vm down, second it verifies the vms are shut down ( user intervention ), third it will snapshot each vm in order and finally will power each vm back on. This is the safest way I have been able to find to do snapshots. 

#Connecting to VI-Server

Connect-Viserver -Server vCenterServer


$VMs = get-content "C:\Lists\vms.txt"

$Today = (Get-Date).ToString(“MM-d-yy”)

$SnapshotName = "$Today - Snapshot"


#This Function Shutsdown the VM's in the $VMs List

Function Shutdown{

foreach ($VM in $VMs){

get-vm -Name $VM | Shutdown-VMGuest -confirm:$false

Write-Host "Shutting $VM down."


Write-Host "Waiting 2 minutes for VM's to shutdown"

Sleep 120


#This Function Lists Power State of all the VMs then Verifies with the User that all VMs are shutdown

Function ShutdownVerify{

Write-Host "Verifying all VM's in $VMs are Powered Off."

foreach ($VM in $VMs){

$pwr = (Get-VM $VM).PowerState

if ($pwr -eq "PoweredOn"){

Write-Host -Foregroundcolor red "$VM is $Pwr"

}elseif ($pwr -eq "PoweredOff"){

Write-Host -Foregroundcolor green "$VM is $Pwr"



$u = Read-Host = "Any VMs Still Powered on? [Yes] or [No] (Case Sensitive)"

if ($u -match "No"){

Write-Host "Running Snapshot Script...."

}elseif ($u -match "Yes") {

Write-Host "Waiting 2 minutes..."

Sleep 120




#This Function Snapshots each server in the $VMs list.

Function Snapshot{

ForEach ($VM in $VMs)


#Create snapshot for today

New-Snapshot -Name $SnapshotName -VM $VM

Write-host "$VM Snapped"


Sleep 5


#This Function Power's on all the VMs in the $VMs List

Function PowerOn{

foreach ($VM in $VMs){

Write-Host "Starting $VM"

Start-VM -VM $VM

Write-Host "$VM started"



#Calling each function in order





No comments:

Post a Comment