#PSTip Overriding the ToString() Method

Note: This tip requires PowerShell 2.0 or above.

In this very helpful tip, Bartek shown us how to create a custom object using the New-Module cmdlet and how to constrain the data the object can hold. Bartek ‘s object represents a user, and almost every time I consume  a “user” object the information I care about the most is the user’s full name. So I was wondering what would be the most convenient way to get such information and I realized I want to be able to do “$User is now logged on.” and get “John Doe is now logged on.”, but I’ve tried it and got  “@{BirthDate=12/17/1978 00:00:00; FirstName=John; LastName=Doe} is now logged on.”.

So I experimented with it and it turns out all I had to do is define (and export) a ToString function which will output the correct data when the variable will be embedded inside a string.

function New-User {

    param (

    New-Module {

        param ( $fn, $ln, $bd )
        [String]$FirstName = $fn
        [String]$LastName = $ln
        [DateTime]$BirthDate = $bd

        function ToString {"$FirstName $LastName" }

        Export-ModuleMember -Variable FirstName, LastName, BirthDate -Function ToString

    } -AsCustomObject -ArgumentList $FirstName,$LastName,$BirthDate


#Create a new user...
PS> $User = New-User -FirstName John -LastName Doe -BirthDate 12/17/1978

#...and use it:
PS> "$User is now logged on."
John Doe is now logged on.

#Not surprisingly it works with other ways of converting to String too:
PS> $User.ToString() + " is the best!"
John Doe is the best!

PS> [string]$User
John Doe

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

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

Leave a Reply

Submit Comment

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