-
Notifications
You must be signed in to change notification settings - Fork 0
/
explain.psm1
72 lines (66 loc) · 2.62 KB
/
explain.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
#requires -Version 2
function Get-CommandExplanation {
$cmdline = $args -join ' '
$tokens =
[System.Management.Automation.PSParser]::Tokenize($cmdline, [ref]$null)
# Assume the first token is a command or alias
$command,$params = $tokens
$command = Get-Command $command.Content -ErrorAction Stop
while ($command.CommandType -eq 'Alias') {
$command = $command.ReferencedCommand
}
# Retain only the arguments
"Command: $command"
# Group parameters and arguments (when applicable)
$parsedParameters =
$params |
ForEach-Object {
$currentParameter = $null
$currentPosition = 0
} {
if ($_.Type -eq 'CommandParameter') {
# First figure out the parameter
$paramString = $_.Content -replace '^-'
if ($paramString.EndsWith(':')) {
$switchParamWithArgument = $true
$paramString = $paramString -replace ':^'
}
$param = $command.ResolveParameter($paramString)
if ($param.SwitchParameter -and !$switchParamWithArgument) {
New-Object PSObject -Property @{
Type = 'Switch'
Name = $param.Name
Value = $true
Position = -1
} | Select-Object Type,Name,Position,Value
} else {
$currentParameter = New-Object PSObject -Property @{
Type = 'Named'
Name = $param.Name
Value = $null
Position = -1
} | Select-Object Type,Name,Position,Value
}
}
if ($_.Type -eq 'CommandArgument') {
if (!$currentParameter) {
# This would be a positional parameter
New-Object PSObject -Property @{
Type = 'Positional'
Name = $null
Position = $currentPosition
Value = $_.Content
} | Select-Object Type,Name,Position,Value
$currentPosition++
} else {
$currentParameter.Value = $_.Content
$currentParameter
$currentParameter = $null
}
}
}
$parsedParameters
}
New-Alias explain Get-CommandExplanation
New-Alias Explain-Command Get-CommandExplanation
Export-ModuleMember -Alias explain,Explain-Command -Function Get-CommandExplanation