Information Technology Reference
In-Depth Information
store information that will be used later in a script. Building on our example in the discussion of
objects, let's say we wish to collect all of the VM objects into a variable for later use:
$vm = Get-VM | Select-Object Name, PowerState
The variable $vm now contains all of the same data that was produced when we ran the one-
liner earlier. You can now simply type $vm into the PowerCLI console and you'll see the same
results. This means you can do a variety of things with the variable later in your console or in
scripts:
$vm | Export-CSV -Path C:\Test\VMs.csv -NoTypeInformation
$vm | Where-Object{$_.PowerState -eq “PoweredOn”}
Keep in mind that there are also global variables already in use with PowerShell and
PowerCLI. You can get a full listing of them with the Get-Variable cmdlet. Most notably, keep
in mind that $host is already in use by the system and cannot be set within your scripts. It is
common to use $vm and $vmhost instead. You'll also learn about $DefaultVIserver in the sec-
tion later in this chapter on connecting to your virtual infrastructure with PowerCLI.
You'll see the use of variables throughout this chapter and when you're looking at code
examples from both VMware and the community. Always be mindful not to use the same vari-
able twice in your script, and try to name the variable so it's easy to discern what information is
located within that container.
Pipeline
At the base of PowerShell's capability is the pipeline . Those coming from a Unix background will
be well versed in the concept of a pipeline. However, PowerShell took the traditional pipeline
and kicked it up a notch. In the past, pipelines were a means to pass text from one command to
another, simplifying the syntax of a given operation. In PowerShell, pipelines are a means to pass
whole .NET objects from one cmdlet to another. This ability greatly increased the power of the
pipeline while simplifying its ability to accomplish almost any administrative action. In short,
this means that as you use PowerCLI cmdlets, you'll be able to pass a Cluster object through the
pipeline and retrieve all of the hosts within that single cluster. In this example, we do so and then
check each VMhost object so that we return only those that are in maintenance mode.
Get-Cluster <cluster name> | Get-VMhost | `
Where{$_.ConnectionState -eq “Maintenance”}
Continuing Pipeline over Multiple Lines
When using PowerShell and the pipeline, you may have lines that do not fi t cleanly on the screen
or your editor. In this topic we use the ` symbol to indicate that the code continues onto the next
line. h is symbol is recognized by PowerShell to continue the current pipeline even though it is
written on a separate line. An attempt is made with each use to make the break logical in order to
maintain the readability of the code.
Search WWH ::




Custom Search