02 May 2012

Hyper-V PowerShell script to change all VMs to Dynamic Memory

If you have a very standardized Hyper-V environment such as VDI implementations you may want to automate setting all the hosts to use dynamic memory.

This heavily modified script changes all the VM on a host to use the predefined RAM values and settings

The original can be found here http://thelazyadmin.com/2012/04/xendesktop-vdi-and-dynamic-memory





# PowerShell Script for changing RAM settings for all machines on the hosts specified


Write-Host("——————————————————–")
Write-Host("This script configures all the VMs on the hosts with dynamic memory.")
Write-Host("")
Write-Host("———————–")
Write-Host("Ensure hat all VMs are tunred off on all the hosts")-foregroundcolor RED
$tmp = Read-Host("Press Enter to continue") 
Write-Host("——————————————————–")




$ServerNames = "hyperv10","hyperv11","hyperv12","hyperv13"  #Enter the list of servernames here
foreach ($ServerName in $ServerNames) {


$Reservation = "512" #Enter Minimum RAM
$Limit = "2048" # Enter Maximum RAM
$Buffer = "20" # Enter Buffer % Default is 20%
$Weight = "5000" # Enter Weight Default is 5000

$VMMS = Get-WmiObject -ComputerName $ServerName -namespace root\virtualization -class Msvm_VirtualSystemManagementService 
$VMs = Get-WmiObject -ComputerName $ServerName -Namespace root\virtualization -class MSVM_ComputerSystem  




Write-Host("———————————-")
Write-Host("Hyper-V Server Name: ", $ServerName) -foregroundcolor Yellow 
Write-Host("———————————-")
foreach ($VM in $VMs) 
              {
              Write-Host("    ",$Vm.ElementName)
              }
$waitstart = 200 
$waitshutdown = 120
$selection = "y"
if ($selection -eq "y")
{
}
              Write-Host("———————–")
              write-host("Setting Dynamic Memory.")
              Write-Host("———————–")
              foreach ($VM in $VMs)
                              { 
if ($VM.ElementName -eq $ServerName) 
{ } else {
$VMSettings = Get-WmiObject -ComputerName $ServerName -Namespace root\virtualization -Query "Associators of {$VM} where ResultClass=Msvm_VirtualSystemSettingData" 
$MemorySettings = Get-WmiObject -ComputerName $ServerName -Namespace root\virtualization -Query "Associators of {$VMSettings} where ResultClass=Msvm_MemorySettingData" 
$MemorySettings.DynamicMemoryEnabled = 1 
$MemorySettings.Reservation = $Reservation
$MemorySettings.VirtualQuantity = $Reservation
$MemorySettings.Limit = $Limit  
Write-Host("Changing memory configuration for ", $VM.ElementName) -foregroundcolor green
$result = $VMMS.ModifyVirtualSystemResources($VM.__PATH, $MemorySettings.psbase.GetText(1)) 
}
                             }




}
 Write-Host("")
 Write-Host("")
 Write-Host("———————–")
 write-host("Script Completed") -foregroundcolor Yellow 
 Write-Host("———————–")



This is my first Hyper-V PowerShell script so any feedback would be great!!


No comments:

Post a Comment