code_junkie

Equivalent of *Nix 'which' command in Powershell?

Nov 10th, 2011
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.98 KB | None | 0 0
  1. New-Alias which get-command
  2.  
  3. "`nNew-Alias which get-command" | add-content $profile
  4.  
  5. gcm notepad
  6.  
  7. gcm note*
  8.  
  9. [27] ยป gcm note*
  10.  
  11. CommandType Name Definition
  12. ----------- ---- ----------
  13. Application notepad.exe C:WINDOWSnotepad.exe
  14. Application notepad.exe C:WINDOWSsystem32notepad.exe
  15. Application Notepad2.exe C:UtilsNotepad2.exe
  16. Application Notepad2.ini C:UtilsNotepad2.ini
  17.  
  18. Function Find-Path($Path, [switch]$All=$false, [Microsoft.PowerShell.Commands.TestPathType]$type="Any")
  19. ## You could comment out the function stuff and use it as a script instead, with this line:
  20. # param($Path, [switch]$All=$false, [Microsoft.PowerShell.Commands.TestPathType]$type="Any")
  21. if($(Test-Path $Path -Type $type)) {
  22. return $path
  23. } else {
  24. [string[]]$paths = @($pwd);
  25. $paths += "$pwd;$env:path".split(";")
  26.  
  27. $paths = Join-Path $paths $(Split-Path $Path -leaf) | ? { Test-Path $_ -Type $type }
  28. if($paths.Length -gt 0) {
  29. if($All) {
  30. return $paths;
  31. } else {
  32. return $paths[0]
  33. }
  34. }
  35. }
  36. throw "Couldn't find a matching path of type $type"
  37. }
  38. Set-Alias find Find-Path
  39.  
  40. function which([string]$command) {
  41. begin { $Script:ErrorActionPreference = "SilentlyContinue" }
  42. process {
  43. if(!$_) { $_ = $command }
  44.  
  45. Microsoft.PowerShell.CoreGet-Command $_ |
  46. sort {
  47. if($_.CommandType -match "ExternalScript|Application") {
  48. 1000 + [array]::IndexOf( (Get-Content Env:Path).Split(";"),
  49. [IO.Path]::GetDirectoryName($_.Definition) )
  50. } else {
  51. [int]$_.CommandType
  52. }
  53. } | Select -first 1 # only return the first item
  54. }
  55. }
  56.  
  57. ($Env:Path).Split(";") | Get-ChildItem -filter notepad
Add Comment
Please, Sign In to add comment