
close
close
Chance to win $250 in Petri 2023 Audience Survey
A little while back a discussion came up on Twitter about identifying commands with duplicate names. Part of the discussion related to the concept of command precedence. For example, there’s a cmdlet called Get-Process. But what if you also have a function called Get-Process? Which command gets called? PowerShell has a process of command precedence, which you can read about in more detail in About_Command_Precedence.
Here’s the short version, assuming you aren’t using a fully qualified path or file name.
In my Get-Process example, this means the function gets invoked first.
Testing command precedence (Image Credit: Jeff Hicks)
More command precedence testing (Image Credit: Jeff Hicks)
Getting a command (Image Credit: Jeff Hicks)
Getting all versions of Get-Process (Image Credit: Jeff Hicks)
get-command -CommandType function,cmdlet,alias | Sort Name | Out-GridView
Listing duplicate command names (Image Credit: Jeff Hicks)
help wpk\add-childcontrol
Or manually import the module first.
Another option, since I am concerned about duplicate names is to get all commands and group them on their name property.
$cmds = get-command -CommandType function,cmdlet,alias | group Name
Many commands will only be listed once. The $cmds variable is a GroupInfo object, which has a Count property. Here’s a sample.
$cmds | sort count -Descending | select -first 3
Listing some duplicate command names (Image Credit: Jeff Hicks)
Getting a command (Image Credit: Jeff Hicks)
Checking grouped results (Image Credit: Jeff Hicks)
$dupes = get-command -CommandType function,cmdlet,alias | group Name | where {$_.count -gt 1} | Sort count –Descending
Here’s a sampling of the results.
A sample of duplicate names (Image Credit: Jeff Hicks)
$dupes.group | group source | sort count -Descending
The group property will give me all of the commands, which I can then regroup on their source property and finally sort on the count property.
Grouping duplicates by source (Image Credti: Jeff Hicks)
import-module PowerShellPack -Prefix pp
Now all of the commands in the PowerShellPack module have a noun prefix of pp.
Viewing import commands with a prefix (Image Credit: Jeff Hicks)
Testing prefixed commands (Image Credit: Jeff Hicks)
Grouping duplicate commands by type (Image Credit: Jeff Hicks)
More in PowerShell
Most popular on petri