Add Custom Methods and Properties to Objects

1. Problem

You have an object and want to add your own custom properties or methods (members) to that object.

2. Solution

Use the Add-Member cmdlet to add custom members to an object.

3. Discussion

The Add-Member cmdlet is extremely useful in helping you add custom members to individual objects. For example, imagine that you want to create a report from the files in the current directory, and that report should include each file’s owner. The Owner property is not standard on the objects that Get-ChildItem produces, but you could write a small script to add them, as shown in Example 3-4.

Example 3-4. A script that adds custom properties to its output of file objects

Code View: Scroll / Show All

##############################################################################
## Get-OwnerReport.ps1
##
## Gets a list of files in the current directory, but with their owner added
## to the resulting objects.
##
## Example:
##    Get-OwnerReport
##    Get-OwnerReport | Format-Table Name,LastWriteTime,Owner
##############################################################################

$files = Get-ChildItem
foreach($file in $files)
{
    $owner = (Get-Acl $file).Owner
    $file | Add-Member NoteProperty Owner $owner
    $file
}


                                        

For more information about running scripts, see Section 1.1, “Run Programs, Scripts, and Existing Tools.”

Although it is most common to add static information (such as a NoteProperty), the Add-Member cmdlet supports several other property and method types—including AliasProperty, ScriptProperty, CodeProperty, CodeMethod, and ScriptMethod. For a more detailed description of these other property types, see “Working with the .NET Framework” in Appendix A, as well as the help documentation for the Add-Member cmdlet.

Although the Add-Member cmdlet lets you to customize specific objects, it does not let you to customize all objects of that type. For information on how to do that, see the following section Section 3.12, “Add Custom Methods and Properties to Types.”

3.1. Calculated properties

Calculated properties are another useful way to add information to output objects. If your script or command uses a Format-Table or Select-Object command to generate its output, you can create additional properties by providing an expression that generates their value. For example:

Code View: Scroll / Show All

        Get-ChildItem |
          Select-Object Name,
              @{Name="Size (MB)"; Expression={ "{0,8:0.00}" -f ($_.Length / 1MB) } }


                                        

In this command, we get the list of files in the directory. We use the Select-Object command to retrieve its name and a calculated property called Size (MB). This calculated property returns the size of the file in megabytes, rather than the default (which is bytes).

Tags: , , , , , , , , , ,