Using PowerCLI to set CPU/Memory reservation on VM´s in vSphere

I have made a function to set reservations on VM´s in PowerCLI. The function takes a VM as parameter and also percentage of CPU and Memory you want to reserve.

The function checks the Mhz of the physical CPU from the Host the VM is running on and makes the reservation from this.

In the function I can set both memory and cpu reservation or just one of them

here is a screendump of the function being used

and here is the PowerCLI

function Set-VMReservation{
<#
.SYNOPSIS
Set VM Reservation on Memory and/or CPU

.DESCRIPTION
Use this function set VM reservations 

.PARAMETER MemoryMB
Use this parameter to set the percent of memory reserved for the VM

.PARAMETER CpuMhz
Use this parameter to set the percent of CPU Mhz from the host CPU to be reserved

.NOTES
Author: Niklas Akerlund
Date: 2012-07-19
#>
    param (
   [Parameter(Position=0,Mandatory=$true,HelpMessage="A VM",
    ValueFromPipeline=$True)]
    $VM,
	$MemoryMB = 0,
	$CpuMhz = 0
    )
	$VM = Get-VM $VM
	if ($MemoryMB -ne 0 -and $CpuMhz -ne 0){
		$MemoryMB = $MemoryMB/100
		[int]$MemoryMB = $VM.MemoryMB*$MemoryMB
		$CpuMhz = $CpuMhz/100
		[int]$CpuMhz = ([math]::truncate(((Get-VMHost -id $VM.extensiondata.summary.runtime.host).ExtensionData.Hardware.CpuInfo.hz)/1000000))*$VM.NumCpu*$CpuMhz
		$VM | Get-VMResourceConfiguration |Set-VMResourceConfiguration -CpuReservationMhz $CpuMhz -MemReservationMB $MemoryMB
	}elseif ($MemoryMB -ne 0 -and $CpuMhz -eq 0){
		$MemoryMB = $MemoryMB/100
		[int]$MemoryMB = $VM.MemoryMB*$MemoryMB
		$VM | Get-VMResourceConfiguration |Set-VMResourceConfiguration -MemReservationMB $MemoryMB
	}elseif ($MemoryMB -eq 0 -and $CpuMhz -ne 0){
		$CpuMhz = $CpuMhz/100
		[int]$CpuMhz = ([math]::truncate(((Get-VMHost -id $VM.extensiondata.summary.runtime.host).ExtensionData.Hardware.CpuInfo.hz)/1000000))*$VM.NumCpu*$CpuMhz
		$VM | Get-VMResourceConfiguration |Set-VMResourceConfiguration -CpuReservationMhz $CpuMhz
	}elseif ($MemoryMB -eq 0 -and $CpuMhz -eq 0){
		$VM | Get-VMResourceConfiguration |Set-VMResourceConfiguration -CpuReservationMhz 0 -MemReservationMB 0
	}
}

In this example I have set the CPU reservation to 60 % and Memory to 40 %

Leave a comment

name*

email* (not published)

website