Method overriding in PowerShell


During a workshop of PowerShell a student made the following great question: "You told me that PowerShell is object-oriented, but I didn't see anything about methods overrinding. is that possible in PowerShell? "

That was an excellent question, for more details about objects in the PoweShell see PowerShell | Objects.

The answer is that there is a way to do that. Let's say I want to create a function that overwrite the Get-Process cmdlet. The standard return of this command would be something like the following:

To override this cmdlet, you simply create the following function:

function Get-Process ()
{
Write-Host "this is an example of function overloading in powershell"-ForegroundColor Green
Microsoft.powershell. Management\Get-Process | FT id, name,
@ {n = "Virtual Memory (MB)"; e = {[Math]:: Round ($ _. VM/1 MB, 2)}},
@ {n = "Private Bytes (MB)"; e = {[Math]:: Round ($ _. PrivateMemorySize/1 MB, 2)}},
@ {n = "Working Set (MB)"; e = {[Math]:: Round ($ _. Workingset/1 MB, 2)}}
}

Note that the function has the same name as the Get-Process cmdlet with the difference that to run the Get-Process the original namespace of the same was used to avoid recursion.

The function returns a message and formats the return of the Get-Process cmdlet where only 4 properties are returned with the value in Megabytes. The result of the execution of the overloaded function in this case is:

 


I hope you enjoyed. Until the next.

Comments (4)

  1. Sean Liming says:

    Interesting trick, but not sure about the recursion statement.

  2. Hi Sean,

    To be able to call the original Get-Process, in this case, you need to use the entire namespace: Microsoft.powershell. ManagementGet-Process.

    If you don't use that, you will receive a stack overflow due a infinite recursive.

  3. Victor Zamora says:

    Very nice tip. But it looks that the technic used here was shadowing, when a narrow scoped member hides a wide scoped member of the same name. Is the equivalent of using the new operator in C# or Shadows operator in VB.

    This method in fact works as a proxy to the original Get-Process.

  4. Perfect. You are right. That is a way to simulate method overriding in PowerShell. 😉

Skip to main content