Powershell – How to override the “get-childItem” command in Powershell

powershell

Could I override this command? I want to do my own job when I execute the "Get-ChildItem" command in Powershell.

Best Answer

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:

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:

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:

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:

  1. Alias
  2. Function
  3. Cmdlet
  4. Native Windows commands