Set VM guest setting via powershell
In todays scenario we had a number of virtual guests that had been provisioned with the wrong settings. This scripts demonstrates how to set vm guest settings via powershell. The VmWare PowerCLI cmdlets enabled us to script the process to save an engineer manually updating each setting. For this to work – you need to have the PowerCLI tool installed and loaded. PowerCLI is a powerful tool when managing a VmWare clustered environment and highly recommended for any administration tools.
Below we have provided 4 examples of changing settings in a batch to reduce administration time. PowerCLI can be used to change many settings, so you are not limited to only these examples.
You will note that we define a new settings “spec” and then define a number of attributes within this spec. Our new spec is then applied to the target VM via the “ReconfigVM” class. VMWare documentation exposes what additional changes can be made within your spec as required.
Note; for many setting changes the VM guest must be powered off.
# Import our list of VMs $VMGuests = get-content VM-guests.txt # Connect to the virtual center server $viserver = "Insert your server name or IP here" $ConnectionResult = connect-viserver $viserver # Cycle through each server listed Foreach ( $VMGuest in $VMGuests ) { # Grab the guest object $GuestObject = Get-vm $VMGuest # Ensure the guest is powered off if ( $GuestObject.PowerState -eq "PoweredOff") { # Build our giant new spec which we will add to below $spec = New-Object VMware.Vim.VirtualMachineConfigSpec # Create variables to set the Logging Flag to false $spec.Flags = New-Object VMware.Vim.VirtualMachineFlagInfo # Here we set the flag to false in our spec we built above $spec.Flags.enableLogging = $false # Create a new values array to set advanced values $Values = new-object vmware.vim.optionvalue # Define our key and value pair $Values.key= "devices.hotplug" $Values.value= "false" # Add it to the giant spec we built $spec.ExtraConfig = $Values #Set our memory for the video card - 16 is the chosen value $MemoryMB = 16 # Create a new config value $Config = New-Object VMware.Vim.VirtualDeviceConfigSpec $VideoAdapter = $GuestObject.ExtensionData.Config.Hardware.Device | Where {$_.GetType().Name -eq "VirtualMachineVideoCard"} # Pass back the object we are editing $Config.device = $VideoAdapter $Config.device.videoRamSizeInKB = $MemoryMB * 1KB $Config.operation = "edit" # Store the config changes in the spec build above again $spec.deviceChange = $Config # Push the VMGuest object to the reconfigure function with the spec we have constructed above. $GuestObject | %{$_.ExtensionData.ReconfigVM($spec)} # Set the memory reservation $result = Get-VMResourceConfiguration -VM $GuestObject | Set-VmResourceConfiguration -MemReservationMB 1536 write-host "VM reconfigured:" $GuestObject.Name } else { write-host "VM is powered ON - skipping:" $GuestObject.Name } }