Wednesday, December 30, 2020

PowerShell: Overriding Methods

The introduction of classes in PowerShell 5.1 gave PowerShell the ability to override methods. Every class in PowerShell is derived from the System.Object base class. The System.Object base class exposes the ToString method which is a virtual method meaning it can be overridden  The previous blog post, PowerShell: Enumerations, contained an example of overriding the ToString method (see line 32):


The SimpleLogEntry class shown above is derived by default from the common base class, System.Common. C# developers will note that there is no use of explicate override keyword required in order to override ToString in the SimpleLogEntry class.

One cmdlet that takes invokes the ToString methods is Write-Host. An excerpt from the documentation for Write-Host (see Write-Host) is as follows showing that the cmdlet invokes ToString for the object passed in as a parameter (the object to be written to output in string form):


The following code (shown in the aforementioned blog post) passed an instance of type, SimpleLogEntry, to the Write-Host cmdlet (line 102):


Invoking Write-Host at line 102 takes in the parameter, $logEntry. Write-Host invokes ToString. The output from two invocations of the Write-Log function (which contains the call to Write-Host) is as follows (two invocations of ToString):




No comments :

Post a Comment