Section 5.5. Calling Methods of the .NET Class Library


5.5. Calling Methods of the .NET Class Library

Although it may not have been readily apparent, MSH has been heavily utilizing the .NET Framework in many of the examples we've seen so far. While an expression like (get-process).Count gives the number we're expecting, the Count part is actually referring to a property that all array classes have: their size.

The dot notation is used to indicate to the shell that we're interested in a specific property of an object. This is the means by which $dt.Day can give the day part of a date. Properties of properties can be expressed by appending another period and property name, as in (get-process msh).Modules.Count, where Modules is a property of Process, and Count is a property of Modules. This sequencing of a property of a property of a property can go to an arbitrary depth, limited only by the complexity of the objects being processed.

Properties aren't the only use for this versatile dot symbol. Because .NET classes typically offer a set of methods that allow some action related to the object they represent, we can also use this notation for invoking methods.

5.5.1. How Do I Do That?

By now, the string class should be familiar, so we'll start there. Strings have a set of methods for string manipulation, including extraction of partial substrings, matching of phrases, and search and replace. Like accessing a property, methods are called by using a dot between the variable name and the method name. A method invocation also requires a pair of parentheses after the method name, which may contain zero or more parameters separated by commas. Some methods are overloaded, meaning that they may behave slightly differently based on their parameters:

     MSH D:\MshScripts> $a = "Hello, World!"     MSH D:\MshScripts> $a.Substring(7)     World!     MSH D:\MshScripts> $a.Substring(0, 5)     Hello     MSH D:\MshScripts> $a.StartsWith("He")     True     MSH D:\MshScripts> $b = $a.Replace("World", "everyone")     MSH D:\MshScripts> $b     Hello, everyone!

Some classes also expose what are known as static methodsand static properties. Instead of operating on a particular object, they can be called or used from the class directly. In these cases, a double colon (::) is used between the class name and its static method or property:

     MSH D:\MshScripts> $currentTime = [System.DateTime]::Now     # equivalent to get-date     MSH D:\MshScripts> [System.Diagnostics.Process]::Start("calc.exe")     # just "calc.exe" is easier, but this illustrates the point

Finally, there's one more cmdlet to meet: new-object. For .NET types, new-object creates an object when given a class name. If additional parameters are supplied, they are used to identify a class constructor with matching parameters.

     MSH D:\MshScripts> $myVersion = new-object System.Version 1,2,3,4     MSH D:\MshScripts> $myVersion     Major  Minor  Build  Revision     -----  -----  -----  --------     1      2      3      4

5.5.2. What Just Happened?

If this is your first encounter with object-oriented programming and the .NET Framework, don't give up hope. Methods are very similar to MSH functions in that they take a set of parameters and usually return a value after doing some work. Remember, we've been working with objects all along and cmdlets, like get-member, remain useful when exploring the Class Library.

Classes in the Class Library usually include a set of methods that are useful for working on the data they represent. For example, we saw how the String class contains methods for the extract part of a string, whereas the DateTime class provides methods for working with dates, such as adding days and months (while respecting month and year boundaries). The method names themselves describe, in a general sense, what effect they have. For example, the Substring operation of the String class does imply that we'll get back only part of the string. However, there are a number of ways this could be achieved, and this is where method overloading comes in. An overloaded method will do one of a related set of operations, depending on the parameters it is given. Whether we want all of a string after a certain point, just a middle fragment, or just the start of it, we use Substring to get it. get-member can be used to show the different overloads for a given method:

     MSH D:\MshScripts> [string]"" | get-member -MemberType Method | where-object { $_.Name -eq "substring" } | format-list     TypeName   : System.String     Name       : Substring     MemberType : Method     Definition : System.String Substring(Int32 startIndex), System.String                  Substring                  (Int32 startIndex, Int32 length)

For each class in the Class Library, there is documentation on MSDN that describes the methods and their behavior in detail and lists any overloaded methods. Static methods and properties generally apply to a whole family of objects rather than to a specific instance. Think of the DateTime class, for instance. While methods like AddDays and AddMonths would act on a particular date, the current date, for example, is a more general idea across all DateTime classes. To use static methods and properties, it is not necessary to have a real object in hand (so there will be no $obj type of variable); instead, the :: syntax is used. Its use is similar to the dot notation (the :: is placed after the class name and before the method or property), but it explicitly tells the shell whether we're interested in using a static property or method.

new-object is very similar to the [] notation. new-object is convenient for use in a script where the class constructor performs some useful configuration or setup of the object it creates. In the System.Version case, the constructor takes four parameters representing major, minor, build, and revision numbers, respectively. Instead of having to do $myVersion.Major = 1; $myVersion.Minor = 2; and so on, use the new-object syntax, which is usually more compact.

5.5.3. What About ...

... Using the new-object technique to write shell extensions? Although the new-object allows .NET types to be used and manipulated by the shell, it's not always the best approach for building an extension. If you have some existing business logic library that would be valuable from within the shell without changes, then new-object style could be very effective.

5.5.4. Where Can I Learn More?

The .NET Class Library documentation is available at http://msdn.microsoft.com and gives a list of properties and methods available for every class in the library. All of the public methods listed in the output of get-member have accompanying documentation on this site.

As expected, the get-help output for new-object also lists the options available when creating objects with the cmdlet.




Monad Jumpstart
Monad Jumpstart
ISBN: N/A
EAN: N/A
Year: 2005
Pages: 117

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net