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.