Reader small image

You're reading from  Learning PowerCLI - Second Edition

Product typeBook
Published inFeb 2017
Publisher
ISBN-139781786468017
Edition2nd Edition
Right arrow
Author (1)
Robert van den Nieuwendijk
Robert van den Nieuwendijk
author image
Robert van den Nieuwendijk

Robert van den Nieuwendijk is an IT veteran from the Netherlands with over thirty years of experience in Information Technology. He holds a bachelor degree in software engineering. After working a few years as a programmer of air traffic control and vessel traffic management systems, he started his own company Van den Nieuwendijk Informatica in 1988. Since then he has worked as a freelance systems administrator of OpenVMS, Windows Server, Linux, and VMware vSphere systems, for Dutch governmental organizations and cloud providers. During winter he is also a ski and snowboard instructor at an indoor ski school. With his background as a programmer, he always tries to make his job easier by writing programs or scripts to perform repeating tasks. In the past, he used the C programming language, OpenVMS DCL, Visual Basic Script and KiXtart to do this. Now, he uses Microsoft PowerShell and VMware PowerCLI for all of his scripting work. Robert is a frequent contributor and moderator at the VMware VMTN Communities. Since 2012 VMware awarded him the vExpert title for his significant contributions to the community and a willingness to share his expertise with others. He has a blog at http://rvdnieuwendijk.com where he writes mainly about VMware PowerCLI, Microsoft PowerShell, and VMware vSphere. If you want to get in touch with Robert, then you can find him on Twitter. His username is @rvdnieuwendijk. Robert is also the author of Learning PowerCLI, Packt Publishing.
Read more about Robert van den Nieuwendijk

Right arrow

Chapter 3. Working with Objects in PowerShell

PowerShell is an object-oriented shell. Don't let this scare you because if you know how to work with PowerShell objects, it will make your life much easier. Objects in PowerShell have properties and methods, just like objects in real life. For example, let's take a computer and try to see it as an object. It has properties such as the manufacturer, the number of CPUs, the amount of memory, and the type of computer (for example, server, workstation, desktop, or laptop). The computer also has methods, for example, you can switch the computer on and off. Properties and methods together are called members in PowerShell. In Chapter 2 , Learning Basic PowerCLI Concepts, you already saw the Get-Member cmdlet that lists the properties and methods of a PowerShell object. In this chapter, you will learn all of the ins and outs of PowerShell objects. We will focus on the following topics:

  • Using objects, properties, and methods

  • Expanding variables and subexpressions...

Using objects, properties, and methods


In PowerCLI, even a string is an object. You can list the members of a string object using the Get-Member cmdlet that you have seen before. Let's go back to our example from Chapter 2 , Learning Basic PowerCLI Concepts. First, we create a string Learning PowerCLI and put it in a variable named $String. Then, we take the $String variable and execute the Get-Member cmdlet using the $String variable as the input:

PowerCLI C:\> $String = "Learning PowerCLI"
PowerCLI C:\> Get-Member -Inputobject $String

You can also use the pipeline and do it in a one-liner:

PowerCLI C:\> "Learning PowerCLI" | Get-Member

The output will be as follows:

    TypeName: System.String
Name             MemberType            Definition
----             ----------            ----------
Clone            Method                System.Object Clone(), Syst...
CompareTo        Method                int CompareTo(System.Object...
Contains         Method                bool Contains...

Expanding variables and subexpressions in strings


In PowerShell, you can define a string with single or double quotes. There is a difference between these two methods. In a single-quoted string, variables and subexpressions are not expanded, whereas, in a double-quoted string, they are expanded.

Let's look at an example of variable expansion in a double-quoted string:

PowerCLI C:\> $Number = 3
PowerCLI C:\> "The number is: $Number"
The number is: 3

In the preceding example, the string is defined with double quotes, and the $Number variable is expanded. Let's see what happens if you use single quotes:

PowerCLI C:\> $Number = 3
PowerCLI C:\> 'The number is: $Number'
The number is: $Number

Using a single-quoted string, PowerShell doesn't expand the $Number variable. Let's try to put the number of virtual CPUs of a virtual machine in a double-quoted string:

PowerCLI C:\> $vm = Get-VM -Name dc1
PowerCLI C:\> "The number of vCPU's of the vm is: $vm.NumCpu"
The number of vCPU's...

Using here-strings


Until now, you have only seen single-line strings in this book. PowerShell has a so-called here-string that spans multiple lines. You use @" or @' to start the here-string and "@ or '@ to finish the here-string. The @" or @' must be at the end of a line and the "@ or '@ must be at the beginning of the line that terminates the here-string. As in single-line strings, variables and subexpressions are expanded in double-quoted here-strings and are not expanded in single-quoted here-strings.

The following command creates a here-string that spans two lines and puts the here-string in the $s variable:

PowerCLI C:\> $s = @"
>> Learning PowerCLI
>> is a lot of fun!
>> "@
>> $s
>>
Learning PowerCLI
is a lot of fun!

Using the pipeline


In PowerShell, you can use the output of one command as input for another command by using the vertical bar (|) character. This is called using the pipeline. The vertical bar character, in PowerShell, is called the pipe character. In PowerShell, complete objects pass through the pipeline. This is different from cmd.exe or a Linux shell where only strings pass through the pipeline. The advantage of passing complete objects through the pipeline is that you don't have to perform string manipulations to retrieve property values.

Using the ByValue parameter binding

You have already seen some examples of using the pipeline in preceding sections of this book. For example:

PowerCLI C:\> Get-VM | Get-Member

In this example, the output of the Get-VM cmdlet is used as the input for the Get-Member cmdlet. This is much simpler than the following command, which gives you the same result:

PowerCLI C:\> Get-Member -InputObject (Get-VM)

You can see that the Get-Member cmdlet accepts...

Using the PowerShell object cmdlets


PowerShell has some cmdlets that are designed to work with all kinds of objects. You can easily recognize them because they all have the noun Object. You can use the Get-Command cmdlet -Noun parameter to find them:

PowerCLI C:\> Get-Command -Noun Object

The preceding command has the following output:

CommandType Name           Version Source
----------- ----           ------- ------
Cmdlet      Compare-Object 3.1.0.0 Microsoft.PowerShell.Utility
Cmdlet      ForEach-Object 3.0.0.0 Microsoft.PowerShell.Core
Cmdlet      Group-Object   3.1.0.0 Microsoft.PowerShell.Utility
Cmdlet      Measure-Object 3.1.0.0 Microsoft.PowerShell.Utility
Cmdlet      New-Object     3.1.0.0 Microsoft.PowerShell.Utility
Cmdlet      Select-Object  3.1.0.0 Microsoft.PowerShell.Utility
Cmdlet      Sort-Object    3.1.0.0 Microsoft.PowerShell.Utility
Cmdlet      Tee-Object     3.1.0.0 Microsoft.PowerShell.Utility
Cmdlet      Where-Object   3.0.0.0 Microsoft.PowerShell.Core 

In the...

Creating your own objects


There are several ways to create new objects in PowerCLI. In fact, you have already been creating new objects by using the Select-Object -Property command. In the following section, you will learn more ways to create new objects.

Using the New-Object cmdlet

PowerShell has its own cmdlet to create objects: New-Object. You can use this cmdlet to create a Microsoft .NET Framework or COM object.

The New-Object cmdlet has the following syntax. The first parameter set is for creating a Microsoft .NET Framework object:

New-Object [-TypeName] <String> [[-ArgumentList] <Object[]>]
    [-Property <IDictionary>] [<CommonParameters>]

The -TypeName parameter is required.

The second parameter set is for creating a COM object:

New-Object [-ComObject] <String> [-Property <IDictionary>]
    [-Strict] [<CommonParameters>]

The -ComObject parameter is required.

Using a hash table to create an object

One way to create a Microsoft .NET Framework...

Using COM objects


You can also use the New-Object cmdlet to create an instance of a COM object. COM objects were used a lot in VBScript. In PowerShell, you can still use them to do things that you cannot do in native PowerShell. The following example will use the SAPI.SpVoice COM object to output a text as voice. It will say The script is finished. Append this piece of code at the end of your PowerCLI script, and you will hear your computer say that the script is finished so that you don't have to keep watching your computer screen. Isn't this cool?

PowerCLI C:\> $Voice = New-Object -ComObject SAPI.SpVoice
PowerCLI C:\> $Voice.Speak("The script is finished.") | Out-Null

The output of the $Voice.Speak() method is piped to the Out-Null cmdlet to suppress output to the screen. The Out-Null cmdlet sends the output to the NULL device, which is the same as deleting it.

You can get a list of all of the COM objects on your computer with the following PowerShell code:

Get-ChildItem -Path HKLM...

Summary


In this chapter, you learned how to use PowerShell objects, their properties, and methods. You saw variable and subexpression expansion in strings and here-strings. You learned about the PowerShell pipeline and parameter binding using the ByValue or ByPropertyName parameter binding types. You learned how to use the PowerShell object cmdlets: Select-Object, Where-Object, ForEach-Object, Sort-Object, Measure-Object, Group-Object, Compare-Object, Tee-Object, and New-Object. We looked at different methods to create new objects. Finally, you saw an example of how to use COM objects. In the next chapter, you will learn how to manage VMware vSphere Hosts with PowerCLI.

lock icon
The rest of the chapter is locked

Unlock this book and the full library FREE for 7 days

Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
You have been reading a chapter from
Learning PowerCLI - Second Edition
Published in: Feb 2017Publisher: ISBN-13: 9781786468017
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime

Author (1)

author image
Robert van den Nieuwendijk

Robert van den Nieuwendijk is an IT veteran from the Netherlands with over thirty years of experience in Information Technology. He holds a bachelor degree in software engineering. After working a few years as a programmer of air traffic control and vessel traffic management systems, he started his own company Van den Nieuwendijk Informatica in 1988. Since then he has worked as a freelance systems administrator of OpenVMS, Windows Server, Linux, and VMware vSphere systems, for Dutch governmental organizations and cloud providers. During winter he is also a ski and snowboard instructor at an indoor ski school. With his background as a programmer, he always tries to make his job easier by writing programs or scripts to perform repeating tasks. In the past, he used the C programming language, OpenVMS DCL, Visual Basic Script and KiXtart to do this. Now, he uses Microsoft PowerShell and VMware PowerCLI for all of his scripting work. Robert is a frequent contributor and moderator at the VMware VMTN Communities. Since 2012 VMware awarded him the vExpert title for his significant contributions to the community and a willingness to share his expertise with others. He has a blog at&nbsp;http://rvdnieuwendijk.com where he writes mainly about VMware PowerCLI, Microsoft PowerShell, and VMware vSphere. If you want to get in touch with Robert, then you can find him on Twitter. His username is @rvdnieuwendijk. Robert is also the author of Learning PowerCLI, Packt Publishing.
Read more about Robert van den Nieuwendijk