Information Technology Reference
In-Depth Information
We'll build this example in steps. First, you've probably guessed that you can use the Get-
ResourcePool, Get-VM, and Get-VMGuest cmdlets to create a list of VM guest OS objects in the
resource pool:
Get-ResourcePool <ResourcePoolName> | Get-VM | Get-VMGuest
Next, you would need to i lter the output to return only those objects identii ed as Microsoft
Windows guest OSes. As you saw in a previous example, you can use the Where-Object cmdlet
to i lter the output list in a pipeline:
Get-ResourcePool <ResourcePoolName> | Get-VM | Get-VMGuest |
Where-Object { $_.OSFullName -match ″^Microsoft Windows.*″ }
This should do it, right? To i nish the command, you should be able to add the Move-VM
cmdlet and move the VMs to the destination resource pool. Unfortunately, that won't work.
You're working with objects with PowerShell, and a VM guest OS object—which is what is being
returned by the Get-VMGuest cmdlet—isn't the kind of object that the Move-VM cmdlet will
accept as input.
Instead, you'll have to use a multiline script for this, as shown in Listing 14.1.
Listing 14.1: A PowerCLI script to selectively move VMs to a new resource pool
$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″) } }
Again, we'll break down the script so that it is easier to understand:
Line 1 uses the Get-VM and Get-ResourcePool cmdlets to retrieve a list of VM objects in
the specii ed resource pool. That list of VM objects is stored in the $VMs variable.
Line 2 creates a loop that operates for each of the objects in the $VMs variable. Each indi-
vidual VM object is stored as $vm.
Line 3 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.
Line 4 tests to see whether the OSFullName property of the $vmguest object matches a
string starting with Microsoft Windows.
Line 5 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.
If you were to save the script in Listing 14.1 as MoveWindowsVMs.ps1, then you could run it in
PowerCLI like this:
<Path to Script>\MoveWindowsVMs.ps1
Search WWH ::




Custom Search