-
Notifications
You must be signed in to change notification settings - Fork 1
/
PsWhich.psm1
121 lines (108 loc) · 2.77 KB
/
PsWhich.psm1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
function Get-CommandPath
{
Param (
[switch]$All,
[parameter(Mandatory=$true)]
[string]$Path
)
$pattern = "^(\\|\.\.?|[a-z]:\\)"
if ($Path -match $pattern)
{
$pattern = "\\[^\\]+\.(" + [string]::Join("|", $env:PATHEXT.replace(".","").split(";")) + "|PS1)$"
if (-not ($Path -match $pattern))
{
Not-Found($Path)
return
}
}
try {
$cmd = Get-Command $Path -ErrorAction Stop
}
catch [Exception]
{
Not-Found($Path)
return
}
switch ($cmd.CommandType)
{
"Alias"
{
Write-Output($Path + ": aliased to " + $cmd.Definition)
break
}
"Cmdlet"
{
Write-Output($Path + ": Cmdlet")
break
}
{"Filter", "Function", "Workflow" -contains $_}
{
Write-Output $cmd.Definition
break
}
default #Application, ExternalScript, Script
{
if (-not $All)
{
Write-Output $cmd.Definition
}
break
}
}
if ($All)
{
Search-Path($Path)
}
}
function Search-Path
{
Param(
[parameter(Mandatory=$true)]
[string]$Target)
$pattern = "[^\\]+\.(" + [string]::Join("|", $env:PATHEXT.replace(".","").split(";")) + "|PS1)$"
if (-not ($Target -match $pattern))
{
$Include = ("*" + $env:PATHEXT.replace(";",";*")).split(";")
$Include += "*.PS1"
$Target += ".*"
}
$env:PATH.split(";").ForEach(
{
$BasePath = $_
$SearchPath = Join-Path $BasePath $Target
try {
$ChildItem = Get-ChildItem $SearchPath -Include $Include -ErrorAction Stop
if (-not ($null -eq $ChildItem))
{
If ($ChildItem -is [array])
{
$ChildItem.ForEach({Write-Output(Join-Path $BasePath $_)})
}
else
{
Write-Output(Join-Path $BasePath $ChildItem.Name)
}
}
}
catch [Exception]
{
return
}
}
)
}
function Get-AllCommandPath
{
Param (
[parameter(Mandatory=$true)]
[string]$Path
)
Get-CommandPath -All $Path
}
function Not-Found($Path)
{
Write-Output($Path + " not found")
}
Set-Alias which Get-CommandPath
Set-Alias wherecmd Get-AllCommandPath
Export-ModuleMember -Function Get-CommandPath, Get-AllCommandPath -Alias "Which", "wherecmd"