Saturday, 28 July 2012

VMware Automation Tools: PowerCLI - Part3


When your virtual environment starts scaling out, manageability using GUI becomes limited. This is due to the fact that you need to spend more time on doing routine repetitive activities which again will increase the risk of human error.

I am listing below some basic scripts that I found useful during my studies. I believe from this stage you may start diving in PowerCLI ocean to automate your environment nicely.

Migrating VMs Using vMotion (Both Powered-on & Powered-off)

Get-VMHost <FirstHost> | Get-VM | Move-VM –destination <Get-VMHost <SecondHost>>

Disconnecting Media Drives

Get-Datacenter | Get-VM | ForEach ( $_ ) { Get-CDDrive $_ | Where { $_.IsoPath.Length -gt 0 -OR $_.HostDevice.Length -gt 0 } | Set-CDDrive -NoMedia -Confirm:$False }

Reconfiguring Virtual Machine Networking

Get-VM | Get-NetworkAdapter | Where-Object { $_.NetworkName -like “OldPortGroupName” } | Set-NetworkAdapter –NetworkName “NewPortGroupName” –Confirm:$false

Migrate VMs Selectively

$VMs = Get-VM –Location (Get-ResourcePool Infrastructure)
foreach ($vm in $VMs) {
$vmguest = Get-VMGuest –VM $vm
if ($vmguest.OSFullName –match “ˆMicrosoft Windows.*”) {
Move-VM –VM $vm –Destination (Get-ResourcePool “Windows VMs”) } }

  • The first line uses the Get-VM and Get-ResourcePool cmdlets to retrieve a list of VM objects in the specified resource pool. That list of VM objects is stored in the $VMs variable.
  • The second line creates a loop that operates for each of the objects in the $VMs variable. Each individual VM object is stored as $vm.
  • The third line uses the Get-VMGuest cmdlet with the $vm variable to retrieve the guest OS object for that VM object and store the result in the $vmguest variable.
  • The fourth line tests to see whether the OSFullName property of the $vmguest object matches a string starting with “Microsoft Windows.”
  • The fifth line executes only if the test on the fourth line was successful; if it executes, it uses the Move-VM and Get-ResourcePool cmdlets to move the VM object represented by the $vm variable to the resource pool named Windows VMs.
TIP: When you are writing a script, its very important to make sure that output object type from superseding cmdlet can be used as input object type for proceeding cmdlet. You may write a script which logically will be working, however, it won't due to the fact of mismatch between the types of objects of different cmdlets.


Note: You may save the script and run it later as we mentioned in the beginning using PS scripts section

No comments:

Post a Comment