Modify Cpu and Memory vSphere

From ToWaSo
Jump to navigation Jump to search

Here is a short script to batch modify the CPU-Core count and Memory of a virtual machine using PowerCLI in a vSphere 6 environment (script adopted from the VMware PowerCLI Forums). The script uses a list of virtual machines which are to be modified including the socket count.

Save the following script in a file with the name modifycpumem.ps1 in C:\

Function Enable-MemHotAdd($vm){
    $vmview = Get-vm $vm | Get-View 
    $vmConfigSpec = New-Object VMware.Vim.VirtualMachineConfigSpec

    $extra = New-Object VMware.Vim.optionvalue
    $extra.Key="mem.hotadd"
    $extra.Value="true"
    $vmConfigSpec.extraconfig += $extra

    $vmview.ReconfigVM($vmConfigSpec)
}

Function Enable-vCpuHotAdd($vm){
    $vmview = Get-vm $vm | Get-View 
    $vmConfigSpec = New-Object VMware.Vim.VirtualMachineConfigSpec

    $extra = New-Object VMware.Vim.optionvalue
    $extra.Key="vcpu.hotadd"
    $extra.Value="true"
    $vmConfigSpec.extraconfig += $extra

    $vmview.ReconfigVM($vmConfigSpec)
}
 

$vmlist = Import-CSV C:\CPUList.csv

 
foreach ($item in $vmlist) {
    $vmname = $item.vmname
    Stop-VM -VM $vmname
    }
	
foreach ($item in $vmlist) {

    $vmname = $item.vmname
    $sockets = $item.sockets
	$cpus = [int]$item.sockets * [int]$item.cores
    $mem = [int]$item.mem * 1024
    Enable-MemHotAdd $vmname
	Enable-vCpuHotAdd $vmname
    Set-VM -VM $vmname -CoresPerSocket $sockets -NumCPU $cpus -MemoryMB $mem -Confirm:$false

}

foreach ($item in $vmlist) {
    $vmname = $item.vmname
    Start-VM -VM $vmname 
    }


Create a csv-file with the colums vmname,sockets,cores,mem,comment and save this file with the name CPUList.csv in the C:\ folder. Modify the code for a different folder.

After that start the PowerCLI console in admin mode.


Then you need to connect to the vSphere of the VMs:

Connect-VIServer "Server" -User user -Password pass


After that you can execute the script:

.\modifycpumem.ps1


In some environment you may need to set the execution policy before to run the ps1-script:

set-executionpolicy remotesigned

Also if you get a certificate error when connecting to the vsphere you can set the certificate check to ignore:

Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Confirm:$false