PoshCode Logo PowerShell Code Repository

Get-Command 2.0 by Joel Bennett 4 years ago (modification of post by Joel Bennett view diff)
diff | embed code: <script type="text/javascript" src="http://PoshCode.org/embed/173"></script>download | new post

Finally, a working Which (or Whence) for PowerShell. This function supplants Get-Command and outputs the commands in the correct order — that is, the first one output is the one the shell will use.

  1. ## Which.ps1 - aka Get-Command
  2. ###################################################################################################
  3. ## This ought to be the same as Get-Command, except...
  4. ## This Which function will output the commands ...
  5. ## in the actual order they would be used by the shell
  6. ##################################################################################################
  7. ## Revision History
  8. ## 1.0 - initial release just sorted the Get-Command output by CommandType
  9. ## 2.0 - rewritten to take into account the order of commands in the PATH environment variable
  10. ##################################################################################################
  11. function Get-Command([string]$command) {
  12. begin { $Script:ErrorActionPreference = "SilentlyContinue" }
  13. process {
  14. if(!$_) { $_ = $command }
  15. Microsoft.PowerShell.Core\Get-Command $_ |
  16.    sort {
  17.       if($_.CommandType -match "ExternalScript|Application") {
  18.          1000 + [array]::IndexOf( (Get-Content Env:Path).Split(";"), [IO.Path]::GetDirectoryName($_.Definition) )
  19.       } else {
  20.          [int]$_.CommandType
  21.       }
  22.    }
  23. }
  24. }

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me