Sometimes you may need to make changes to some virtual machine settings via the PowerCLI.
Recently I found on the VMware Community Forum a basic script that changed the memory allocated to a VM. I took the opportunity to get some hands on PowerCLI. I am sure that there are better scripts to achieve the same task, but I just needed the basics to come up with my own variant and get a chance to learn.
In the above mentioned thread, eatvm posted a basic script that:
- Connects to the vcenter server or ESXi host
- Searches for the VM you need to edit and shuts it down if it is switched on
- Edits the memory size to the desired size.
The one I assembled from his script has been made to take arguments directly through the command line and perform additional checks and tasks.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | param ( [string]$server = "", [string]$vmname = "", [string]$mem ="" ) #Connecting to your esxi host/Vcenter Server Write-Host "Connecting to Server : "$server Connect-VIServer $server #Check if VM is powered on $vm = Get-VM -Name $vmname if ($vm.PowerState -eq "PoweredOn") { Write-Host "VM is Switching OFF" $wason=1 $vm | Shutdown-VMGuest -Confirm:$false | Out-Null do { Write-Host "Waiting for VM to Power OFF" $vm = Get-VM -Name $vmname } while ($vm.PowerState -eq "PoweredOn") } #Set memory for vm Write-Host "Setting Memory Size to " $mem " MB" $vm | Set-VM -MemoryMB $mem -Confirm:$false #Start the Virtual Machine if it was Powered ON if ($wason) { Write-Host "Switching the Virtual Machine back On" $vm | Start-VM | Out-Null} Write-Host "Disconnecting from Server : " $server Disconnect-VIserver $server -Confirm:$false Write-Host "Done" |
The above script will use the arguments -server, -vmname and -mem to:
- Connect tot hee Vcenter Server/ESXI host
- look for the virtual machine and, if powered ON, it will shut it down and take a note that it was ON.
- Wait for the VM to shutdown
- Once shutdown, the memory will be resized.
- The virtual machine will be powered back up, if it was on before starting.
- Disconnect from the Vcenter server or ESXi host.
To execute the script you need to save the above code to a ps1. For Example vmmem.ps1. You can also download the file from below.Then open VMware Vsphere Power CLI and browse to the directory you saved the script in.
Type:
./vmmem.ps1 -server <server name> -vmname <VM name> -mem <memory to resize> |
If the Host or vcenter server is not in the PowerCLI Credentails Store, a dialogue asking for the username and password will appear. Type them in and wait for the script to work. When done check the settings in your VSphere Client.
If you have any suggestions to improve the script, please leave a comment or contact me.
The script is available fro download from here vmmem.ps1