Working with the .NET Framework

One feature that gives PowerShell its incredible reach into both system administration and application development is its ability to leverage Microsoft’s enormous and broad .NET Framework.

The .NET Framework is a large collection of classes. Each class embodies a specific concept, and groups closely related functionality and information.

An example of such a class is System.Diagnostics.Process—the grouping of functionality that “provides access to local and remote processes, and enables you to start and stop local system processes.”

Classes contain methods (which allow you to perform operations) and properties (which allow you to access information.)

The terms type and class can be used interchangeably.

Static Methods

[ClassName]::MethodName(parameter list)

Some methods relate only to the concept the class represents. For example, retrieving all running processes on a system relates to the general concept of processes. Methods that apply to the class/type as a whole are called static methods.

For example:

PS >[System.Diagnostics.Process]::GetProcessById(0)

gets the process with the ID of 0 and displays the following output:

Handles  NPM(K)    PM(K)      WS(K)  VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      -----  -----   ------     -- -----------
    0     0      0     16               0 0 Idle

Instance Methods

$objectReference.MethodName(parameter list)

Some methods relate only to specific, tangible realizations (called instances) of a class. An example of this would be a process actually running on the system, as opposed to the general concept of processes. If $objectReference refers to a specific System.Diagnostics.Process (as output by GetProcessById(), for example,), you may want to start it, stop it, or wait for it to exit. Methods that act on instances of a class are called instance methods.

The term object is often used interchangeably with the term instance.

For example:

PS >$process = [System.Diagnostics.Process]::GetProcessById(0)
PS >$process.Refresh()

Stores the process with ID of 0 into the $process variable. It then calls the Refresh() instance method on that specific process.

Tip

To learn about the different sets of parameters (overloads) that a given method supports, type that method name without any parameters:

PS >$now = [DateTime]::Now
PS >$now.AddDays

MemberType          : Method
OverloadDefinitions : {System.DateTime AddDays(Double value)}
TypeNameOfValue     : System.Management.Automation.PSMethod
Value               : System.DateTime AddDays(Double value)
Name                : AddDays
IsInstance          : True

Static Properties

$objectReference.PropertyName

or:

$objectReference.PropertyName = <value>

Like static methods, some properties relate only to information about the concept that the class represents. For example, the System.DateTime class “represents an instant in time, typically expressed as a date and time of day.” It provides a Now static property that returns the current time:

PS >[System.DateTime]::Now
Sunday, July 16, 2006 2:07:20 PM

Although relatively rare, some types allow you to set the value of some static properties.

Instance Properties

$objectReference.PropertyName

or:

$objectReference.PropertyName = <value>

Like instance methods, some properties relate only to specific, tangible realizations (called instances) of a class. An example of this would be an actual instant in time, as opposed to the general concept of dates and times. If $objectReference refers to a specific System.DateTime (as output by [System.DateTime]::Now, for example,) you may want to retrieve its day of week, day, or month. Properties that return information about instances of a class are called instance properties.

For example:

PS >$today = [System.DateTime]::Now
PS >$today.DayOfWeek
Sunday

Stores the current date into the $today variable. It then calls the DayOfWeek instance property on that specific date.

Learning About Types

The two primary avenues for learning about classes and types are the Get-Member cmdlet and the documentation for the .NET Framework.

The Get-Member Cmdlet

To learn what methods and properties a given type supports, pass it through the Get-Member cmdlet.

Working with the Get-Member cmdlet

Action

Result

[<classname>] | get-member –static

All of the static methods and properties of a given type.

$objectReference | get-member –static

All of the static methods and properties provided by the type in $objectReference.

$objectReference | get-member

All of the instance methods and properties provided by the type in $objectReference.

[<classname>] | get-member

All of the instance methods and properties provided by this specific instance of a class called Type.

.NET framework documentation

Another source of information about the classes in the .NET Framework is the documentation itself, available through the search facilities at http://msdn.microsoft.com.

Typical documentation for a class first starts with a general overview, then provides a hyperlink to the members of the class—the list of methods and properties it supports.

Tip

To get to the documentation for the members quickly, search for them more explicitly by adding the term “members” to your MSDN search term:

<classname> members

The documentation for the members of a class lists their methods and properties, and uses an S icon to represent the static methods and properties. Click the member name for more information about that member—including the type of object that the member produces.

Type Shortcuts

When you specify a type name, PowerShell allows you to use a short form for some of the most common types.

PowerShell type shortcuts

Type shortcut

Full classname

[Adsi]

[System.DirectoryServices.DirectoryEntry]

[Hashtable]

[System.Collections.Hashtable]

[PSObject]

[System.Management.Automation.PSObject]

[Ref]

[System.Management.Automation.PSReference]

[Regex]

[System.Text.RegularExpressions.Regex]

[ScriptBlock]

[System.Management.Automation.ScriptBlock]

[Switch]

[System.Management.Automation.SwitchParameter]

[Wmi]

[System.Management.ManagementObject]

[WmiClass]

[System.Management.ManagementClass]

[WmiSearcher]

[System.Management.ManagementObjectSearcher]

[Xml]

[System.Xml.XmlDocument]

[<TypeName>]

[System.<TypeName>]

Creating Instances of Types

$objectReference = New-Object TypeName [parameter list]

Although static methods and properties of a class generate objects, you will often want to create them explicitly yourself. PowerShell’s New-Object cmdlet lets you create an instance of the type you specify. The parameter list must match the list of parameters accepted by one of the type’s constructors, as documented on MSDN.

For example:

$webClient = New-Object Net.WebClient
$webClient.DownloadString("http://search.msn.com")

Most common types are available by default. However, many are available only once you load the library (called the assembly) that defines them. The MSDN documentation for a class includes the assembly that defines it.

To load an assembly, use the methods provided by the System.Reflection.Assembly class:

PS >[Reflection.Assembly]::LoadWithPartialName("System.Web")

GAC   Version        Location
---   -------        --------
True  v2.0.50727     C:WINDOWSassemblyGAC_32(…)System.Web.dll


PS >[Web.HttpUtility]::UrlEncode("http://search.msn.com")
http%3a%2f%2fsearch.msn.com

Warning

The LoadWithPartialName method is unsuitable for scripts that you wish to share with others, or use in a production environment. It loads the most current version of the assembly, which may not be the same as the version you used to develop your script. To load an assembly in the safest way possible, use its fully qualified name with the [Reflection.Assembly]::Load() method.

Interacting with COM Objects

PowerShell allows you to access methods and properties on COM objects the same way you would interact with objects from the .NET Framework. To interact with a COM object, use its ProgId with the –ComObject parameter (often shortened to –Com) on New-Object:

PS >$shell = new-object -Com Shell.Application

PS >$shell.Windows() | select LocationName,LocationUrl

Extending Types

PowerShell supports two ways to add your own methods and properties to any type: the Add-Member cmdlet, and a custom types extension file.

The Add-Member cmdlet

The Add-Member cmdlet allows you to dynamically add methods, properties, and more to an object. It supports the following extensions:

Selected member types supported by the Add-Member cmdlet

Member Type

Meaning

AliasProperty

A property defined to alias another property:

$testObject = [PsObject] "Test"
$testObject | Add-Member "AliasProperty" Count
Length
$testObject.Count

CodeProperty

A property defined by a:

System.Reflection.MethodInfo.

This method must be public, static, return results (nonvoid,) and take one parameter of type PsObject.

NoteProperty

A property defined by the initial value you provide:

$testObject = [PsObject] "Test"
$testObject | Add-Member NoteProperty Reversed tseT
$testObject.Reversed

ScriptProperty

A property defined by the script block you provide. In that script block, $this refers to the current instance:

$testObject = [PsObject] ("Hi" * 100)
$testObject | Add-Member ScriptProperty IsLong {
     $this.Length -gt 100
   }
$testObject.IsLong

PropertySet

A property defined as a shortcut to a set of properties. Used in cmdlets such as Select-Object:

$testObject = [PsObject] [DateTime]::Now
$collection = new-object `
Collections.ObjectModel.Collection``1[System.String]
$collection.Add("Month")
$collection.Add("Year")
$testObject | Add-Member PropertySet MonthYear
$collection
$testObject | select MonthYear

CodeMethod

A method defined by a:

System.Reflection.MethodInfo.

This method must be public, static, and take one parameter of type PsObject.

ScriptMethod

A method defined by the script block you provide. In that script block, $this refers to the current instance, and $args refers to the input parameters:

$testObject = [PsObject] "Hello"
$testObject | Add-Member ScriptMethod IsLong {
     $this.Length -gt $args[0]
   }
$testObject.IsLong(3)
$testObject.IsLong(100)

Custom type extension files

While the Add-Member cmdlet allows you to customize individual objects, PowerShell also supports configuration files that allow you to customize all objects of a given type. For example, you might wish to add a Reverse() method to all strings or a HelpUrl property (based on the MSDN “Url Aliases”) to all types.

PowerShell adds several type extensions to the file types.ps1xml, in the PowerShell installation directory. This file is useful as a source of examples, but you should not modify it directly. Instead, create a new one and use the Update-TypeData cmdlet to load your customizations. The following command loads Types.custom.ps1xml from the same directory as your profile:

$typesFile = join-path (split-path $profile) “Types.Custom.Ps1Xml”Update-TypeData –PrependPath $typesFile

..................Content has been hidden....................

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