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 in strings
  • Using here-strings
  • Using the pipeline
  • Using the PowerShell object cmdlets
  • Creating your own objects
  • Using COM objects

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(string value)
CopyTo           Method                void CopyTo(int sourceIndex...
EndsWith         Method                bool EndsWith(string value)...
Equals           Method                bool Equals(System.Object o...
GetEnumerator    Method                System.CharEnumerator GetEn...
GetHashCode      Method                int GetHashCode()
GetType          Method                type GetType()
GetTypeCode      Method                System.TypeCode GetTypeCode...
IndexOf          Method                int IndexOf(char value), in...
IndexOfAny       Method                int IndexOfAny(char[] anyOf...
Insert           Method                string Insert(int startInde...
IsNormalized     Method                bool IsNormalized(), bool I...
LastIndexOf      Method                int LastIndexOf(char value)...
LastIndexOfAny   Method                int LastIndexOfAny(char[] a...
Normalize        Method                string Normalize(), string ...
PadLeft          Method                string PadLeft(int totalWid...
PadRight         Method                string PadRight(int totalWi...
Remove           Method                string Remove(int startInde...
Replace          Method                string Replace(char oldChar...
Split            Method                string[] Split(Params char[...
StartsWith       Method                bool StartsWith(string valu...
Substring        Method                string Substring(int startI...
ToBoolean        Method                bool IConvertible.ToBoolean...
ToByte           Method                byte IConvertible.ToByte(Sy...
ToChar           Method                char IConvertible.ToChar(Sy...
ToCharArray      Method                char[] ToCharArray(), char[...
ToDateTime       Method                datetime IConvertible.ToDat...
ToDecimal        Method                decimal IConvertible.ToDeci...
ToDouble         Method                double IConvertible.ToDoubl...
ToInt16          Method                int16 IConvertible.ToInt16(...
ToInt32          Method                int IConvertible.ToInt32(Sy...
ToInt64          Method                long IConvertible.ToInt64(S...
ToLower          Method                string ToLower(), string To...
ToLowerInvariant Method                string ToLowerInvariant()
ToSByte          Method                sbyte IConvertible.ToSByte(...
ToSingle         Method                float IConvertible.ToSingle...
ToString         Method                string ToString(), string T...
ToType           Method                System.Object IConvertible....
ToUInt16         Method                uint16 IConvertible.ToUInt1...
ToUInt32         Method                uint32 IConvertible.ToUInt3...
ToUInt64         Method                uint64 IConvertible.ToUInt6...
ToUpper          Method                string ToUpper(), string To...
ToUpperInvariant Method                string ToUpperInvariant()
Trim             Method                string Trim(Params char[] t...
TrimEnd          Method                string TrimEnd(Params char[...
TrimStart        Method                string TrimStart(Params cha...
Chars            ParameterizedProperty char Chars(int index) {get;}
Length           Property              int Length {get;}

You may see that a string has a lot of methods, one property, and a special type of property named ParameterizedProperty. Let's first use the Length property. To use a property, type the object name or the name of the variable containing the object, then type a dot, and finally type the property name. So, for the string, you could use any of the following command lines:

PowerCLI C:> "Learning PowerCLI".Length
17

Or:

PowerCLI C:> $String.Length
17

You may see that the Length property contains the number of characters of the string Learning PowerCLI17 in this case.

Property names in PowerShell are not case-sensitive. So, you could type the following command as well:

PowerCLI C:> $String.length
17

ParameterizedProperty is a property that accepts a parameter value. The ParameterizedProperty char Chars property can be used to return the character at a specific position in the string. You have to specify the position, also named the index, as a parameter to Chars. Indexes in PowerShell start with 0. So, to get the first character of the string, type the following command:

PowerCLI C:> $String.Chars(0)
L

To get the second character of the string, type the following command:

PowerCLI C:> $String.Chars(1)
e

You cannot use -1 to get the last character of the string, as you can do with indexing in a PowerShell array. You have to calculate the last index yourself, and it is calculated by subtracting 1 from the length of the string. So, to get the last character of the string, you can type the following command:

PowerCLI C:> $String.Chars($String.Length - 1)
I

PowerShell has more types of properties, such as AliasProperty, CodeProperty, NoteProperty, and ScriptProperty:

  • AliasProperty is an alias name for an existing property
  • CodeProperty is a property that maps to a static method on a .NET class
  • NoteProperty is a property that contains data
  • ScriptProperty is a property whose value is returned from executing a PowerShell scriptblock

Using methods

Using methods is as easy as using properties. You can type the name of a variable containing the object, then you type a dot, and after the dot, you type the name of the method. For methods, you always have to use parentheses after the method name. For example, to modify a string to all uppercase letters type in the following command:

PowerCLI C:> $String.ToUpper()
LEARNING POWERCLI

Some methods require parameters. For example, to find the index of the P character in the string, you can use the following command:

PowerCLI C:> $String.IndexOf('P')
9

The character P is the tenth character in the Learning PowerCLI string. But because indexes in PowerShell start with 0 and not 1, the index of the P character in the string is 9 and not 10.

A very useful method is Replace that you can use to replace a character or a substring with another character, string, or nothing. For example, let's replace all e characters in the string with a u character:

PowerCLI C:> $String.Replace('e','u')
Luarning PowurCLI

The characters in the method are case-sensitive. If you use an uppercase E, it won't find the letter and will replace nothing. See the following command:

PowerCLI C:> $String.Replace('E','U')
Learning PowerCLI

You can also replace a substring with another string. Let's replace the word PowerCLI with VMware PowerCLI:

PowerCLI C:> $String.Replace('PowerCLI','VMware PowerCLI')
Learning VMware PowerCLI

There is also a -Replace operator in PowerShell. You can use the -Replace operator to do a regular expression-based text substitution on a string or a collection of strings:

PowerCLI C:> $string -Replace 'e','u'
Luarning PowurCLI

Although both have the same name, the string Replace method and the -Replace operator are two different things. There is no -ToUpper operator, as you can see in the following screenshot that gives an error message:

Using methods

You can use more than one method in the same command. Say, you want to replace the word Learning with Gaining, and that you want to remove the characters C, L, and I from the end of the string using the TrimEnd method. Then, you can use the following command:

PowerCLI C:> $String.Replace('Learning','Gaining').TrimEnd('CLI')
Gaining Power
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.156.35