Problem
You have an object and want to add your own custom properties or methods (members) to that object.
Solution
Use the AddMember cmdlet to add custom members to an object.
Discussion
The AddMember 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 GetChildItem produces, but you could write a small script to add them, as shown in
Example 34. A script that adds custom properties to its output of file objects
############################################################################## ## GetOwnerReport.ps1 ## ## Gets a list of files in the current directory, but with their owner added ## to the resulting objects. ## ## Example: ## GetOwnerReport ## GetOwnerReport | FormatTable Name,LastWriteTime,Owner ##############################################################################
$files = GetChildItem foreach($file in $files) {
$owner = (GetAcl $file).Owner
$file | AddMember NoteProperty Owner $owner
$file }
Although it is most common to add static information (such as a NoteProperty), the AddMember 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”, as well as the help documentation for the AddMember cmdlet.
Although the AddMember cmdlet lets you to customize specific objects, it does not let you to customize all objects of that type.
Calculated properties
Calculated properties are another useful way to add information to output objects. If your script or command uses a FormatTable or SelectObject command to generate its output, you can create additional properties by providing an expression that generates their value. For example:
GetChildItem | SelectObject 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 SelectObject 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).
For more information about the AddMember cmdlet, type GetHelp AddMember.
For more information about adding calculated properties, type GetHelp SelectObject or GetHelp FormatTable.