Powershell - How to Override ToString, or any method on an object

Post date: Nov 16, 2011 1:43:03 PM

You need to specify the -Force parameter to override a method on the class, otherwise you get an error saying that the method already exists.

If you override it several times, then it will be the last supplied implementation that will be used.

cls $abba = [System.DateTime]::Now $abba = $abba | Add-Member ScriptMethod ToString { $this.Day } -PassThru -Force $abba.ToString()$abba = $abba | Add-Member ScriptMethod ToString { $this.Month } -PassThru -Force $abba.ToString()