Question:
All I can find online about doing this is to override a cmdlet, but I need to override a windows form event. Here is the C# equivalent of what I need:
1 2 3 4 5 |
protected override Point ScrollToControl(Control activeControl) { return this.AutoScrollPosition; } |
They were saying that you just use the name of the function in the same scope and it will automatically override it, but that is not working for me.
Answer:
If you’re referring to a method, Chris Dent’s answer covers that nicely!
For native PowerShell cmdlets/functions I will copy my answer from ServerFault here:
Yes, you can override Get-ChildItem
or any other cmdlet in Powershell.
Name Your Function The Same
If you make a function with the same name in the same scope, yours will be used.
Example:
1 2 3 4 5 6 7 8 |
Function Get-ChildItem { [CmdletBinding()] param( # Simulate the parameters here ) # ... do stuff } |
Using Aliases
Create your own function, and then create an alias to that function, with the same name as the cmdlet you want to override.
Example:
1 2 3 4 5 6 7 8 9 10 |
Function My-GetChildItem { [CmdletBinding()] param( # Simulate the parameters here ) # ... do stuff } New-Alias -Name 'Get-ChildItem' -Value 'My-GetChildItem' -Scope Global |
This way is nice because it’s easier to test your function without stomping on the built-in function, and you can control when the cmdlet is overridden or not within your code.
To remove the alias:
1 2 |
Remove-Item 'Alias:\Get-ChildItem' -Force |
Know the Command Precedence
about_Command_Precedence lists the order in which commands of different types are interpreted:
If you do not specify a path, Windows PowerShell uses the following
precedence order when it runs commands:
- Alias
- Function
- Cmdlet
- Native Windows commands