24/7/365 Support

Add Custom Methods and Properties to Types

Problem

You want to add your own custom properties or methods to all objects of a certain type.

Solution

Use custom type extension files to add custom members to all objects of a type.

Discussion

Although the AddMember cmdlet is extremely useful in helping you add custom members to individual objects, it requires that you add the members to each object that you want to interact with. It does not allow you to automatically add them to all objects of that type. For that purpose, PowerShell supports another mechanism— custom type extension files.

Type extensions are simple XML files that PowerShell interprets. They let you (as the administrator of the system) easily add your own features to any type exposed by the system. If you write code (for example, a script or function) that primarily interacts with a single type of object, then that code might be better suited as an extension to the type instead.

Since type extension files are XML files, make sure that your customizations properly encode the characters that have special meaning in XML files—such as <, >, and &.

For example, imagine a script that returns the free disk space on a given drive. That might be helpful as a script, but you might find it easier to instead make PowerShell’s PsDrive objects themselves tell you how much free space they have left.

Getting started

If you haven’t already, the first step in creating a types extension file is to create an empty one. The best location for this is probably in the same directory as your custom profile, with the name Types.Custom.ps1xml,

Example 35. Sample Types.Custom.ps1xml file

<?xml version="1.0" encoding="utf8" ?> <Types> </Types>

Next, add a few lines to your PowerShell profile so that PowerShell loads your type extensions during startup:

$typeFile = (JoinPath (SplitPath $profile) "Types.Custom.ps1xml")

UpdateTypeData PrependPath $typeFile By default, PowerShell loads several type extensions from the Types.ps1xml file in PowerShell’s installation directory. The UpdateTypeData cmdlet tells PowerShell to also look in your Types.Custom.ps1xml file for extensions. The PrependPath parameter makes PowerShell favor your extensions over the builtin ones in case of conflict.

Once you have a custom types file to work with, adding functionality becomes relatively straightforward. As a theme, these examples do exactly what we alluded to earlier: add functionality to PowerShell’s PsDrive type.

To support this, you need to extend your custom types file so that it defines additions to the System.Management.Automation.PSDriveInfo type, System.Management.Automation.PSDriveInfo type is the type that the GetPsDrive cmdlet generates.

Example 36. A template for changes to a custom types file

<?xml version="1.0" encoding="utf8" ?> <Types>

<Type>

<Name>System.Management.Automation.PSDriveInfo</Name>

<Members>

add members such as <ScriptProperty> here

</Members> </Type> </Types>

Add a ScriptProperty

A ScriptProperty lets you to add properties (that get and set information) to types, using PowerShell script as the extension language. It consists of three child elements: the Name of the property, the Getter of the property (via the GetScriptBlock child), and the Setter of the property (via the SetScriptBlock child).

In both the GetScriptBlock and SetScriptBlock sections, the $this variable refers to the current object being extended. In the SetScriptBlock section, the $args[0] variable represents the value that the user supplied as the righthand side of the assignment.

AvailableFreeSpace ScriptProperty to PSDriveInfo, and should you access the property, it returns the amount of free space remaining on the drive. When you set the property, it outputs what changes you must make to obtain that amount of free space.

Example 37. A ScriptProperty for the PSDriveInfo type

<ScriptProperty> <Name>AvailableFreeSpace</Name> <GetScriptBlock>

## Ensure that this is a FileSystem drive if($this.Provider.ImplementingType eq [Microsoft.PowerShell.Commands.FileSystemProvider])

{ ## Also ensure that it is a local drive $driveRoot = $this.Root $fileZone = [System.Security.Policy.Zone]::CreateFromUrl(`

$driveRoot).SecurityZone if($fileZone eq "MyComputer") {

$drive = NewObject System.IO.DriveInfo $driveRoot $drive.AvailableFreeSpace }

} </GetScriptBlock> <SetScriptBlock>

## Get the available free space $availableFreeSpace = $this.AvailableFreeSpace

## Find out the difference between what is available, and what they ## asked for. $spaceDifference = (([long] $args[0]) $availableFreeSpace) / 1MB

## If they want more free space than they have, give that message if($spaceDifference gt 0) {

$message = "To obtain $args bytes of free space, " + " free $spaceDifference megabytes." WriteHost $message

} ## If they want less free space than they have, give that message else {

$spaceDifference = $spaceDifference * 1

$message = "To obtain $args bytes of free space, " +

Example 37. A ScriptProperty for the PSDriveInfo type (continued)

" use up $spaceDifference more megabytes." WriteHost $message } </SetScriptBlock> </ScriptProperty>

Add an AliasProperty

An AliasProperty gives an alternative name (alias) for a property. The referenced property does not need to exist when PowerShell processes your type extension file, since you (or another script) might later add the property through mechanisms such as the AddMember cmdlet.

Free AliasProperty to PSDriveInfo, and should also be placed the property, it returns the value of the AvailableFreeSpace property. When you set the property, it sets the value of the AvailableFreeSpace property.

Example 38. An AliasProperty for the PSDriveInfo type

<AliasProperty>

<Name>Free</Name>

<ReferencedMemberName>AvailableFreeSpace</ReferencedMemberName>

</AliasProperty>

Add a ScriptMethod

A ScriptMethod allows you to define an action on an object, using PowerShell script as the extension language. It consists of two child elements: the Name of the property and the Script.

In the script element, the $this variable refers to the current object you are extending. Like a standalone script, the $args variable represents the arguments to the method. Unlike standalone scripts, ScriptMethods do not support the param statement for parameters.

Remove ScriptMethod to PSDriveInfo. Like the other additions, place these customizations within the members section of the template given in Example 36. When you call this method with no arguments, the method simulates removing the drive (through the WhatIf option to RemovePsDrive). If you call this method with $true as the first argument, it actually removes the drive from the PowerShell session.

Example 39. A ScriptMethod for the PSDriveInfo type

<ScriptMethod> <Name>Remove</Name> <Script>

$force = [bool] $args[0]

Example 39. A ScriptMethod for the PSDriveInfo type (continued)

## Remove the drive if they use $true as the first parameter if($force) {

$this | RemovePSDrive } ## Otherwise, simulate the drive removal else {

$this | RemovePSDrive WhatIf } </Script> </ScriptMethod>

Add other extension points

PowerShell supports several additional features in the types extension file, including CodeProperty, NoteProperty, CodeMethod, and MemberSet. Although not generally useful to end users, developers of PowerShell providers and cmdlets will find these features helpful. For more information about these additional features, see the Windows PowerShell SDK, or MSDN documentation.

Looping and Flow Control in Windows PowerShell

As you begin to write scripts or commands that interact with unknown data, the concepts of looping and flow control become increasingly important.

PowerShell’s looping statements and commands let you perform an operation (or set of operations) without having to repeat the commands themselves. This includes, for example, doing something a specified number of times, processing each item in a collection, or working until a certain condition comes to pass.

PowerShell’s flow control and comparison statements let you to adapt your script or command to unknown data. They let you execute commands based on the value of that data, skip commands based on the value of that data, and more.

Together, looping and flow control statements add significant versatility to your PowerShell toolbox.

Help Category:

Get Windows Dedicated Server

Only reading will not help you, you have to practice it! So get it now.

Processor RAM Storage Server Detail
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 1 TB (HDD SATA) Configure Server
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 128 GB (SSD SATA) Configure Server
Intel Atom C2750 2.4 GHz 8c/8t 8 GB DDR3 1× 1 TB (HDD SATA) Configure Server
Intel Xeon E3-1230 v2 3.3 GHz 4c/8t 16 GB DDR3 1× 256 GB (SSD SATA) Configure Server
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 250 GB (SSD SATA) Configure Server

What Our Clients Say