2

#PSTip Overriding the ToString() Method, part II

Note: This tip requires PowerShell 2.0 or above.

In this neat tip Jakub showed a way to control the output of the ToString method by exposing a ToString function. What if you can’t intervene with code or don’t have access to it? Consider the following example:

PS> $gps = Get-Process s* | Select-Object -First 3
PS> "The first 3 service names are: $gps"

The first 3 service names are: System.Diagnostics.Process (SearchIndexer) System.Diagnostics.Process (services) System.Diagnostics.Process (SettingSyncHost)

You can see that when the variable that holds the processes is converted to a string, the ToString method of each process returns the .NET type name followed by the process name in parenthesis. Obviously this is not the way we want to present the data. Let’s see how we can override the ToString method of System.Diagnostics.Process (or any other object):

PS> $gps = Get-Process s* | Select-Object -First 3 | Add-Member -MemberType ScriptMethod -Name ToString -Value {$this.Name} -PassThru -Force
PS> "The first 3 service names are: $gps"

The first 3 service names are: SearchFilterHost SearchIndexer SearchProtocolHost

Excellent, now we get just the names. To introduce your own ToString method you use the Add-Member cmdlet to add a new ScriptMethod called ToString.
In the Value scriptblock, $this represents the current object flowing through the cmdlet and we use it to return the Name of the object (process object in our case).
Because each object already has a ToString method we add the Force switch to override it, and we also add the PassThru switch to write the extended object back to the pipeline.

Filed in: Columns, Tips and Tricks Tags: , , , ,

2 Responses to "#PSTip Overriding the ToString() Method, part II"

Leave a Reply

Submit Comment

© 0276 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: