forked from jdhitsolutions/PSScriptTools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCopy-Command.ps1
304 lines (234 loc) · 8.47 KB
/
Copy-Command.ps1
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
Function Get-CommandParameter {
[cmdletbinding()]
Param(
[Parameter(ValueFromPipeline, Mandatory, HelpMessage = "Enter the name of a command")]
[ValidateNotNullOrEmpty()]
[ValidateScript( {Get-Command $_})]
[string]$Name,
[string[]]$ParameterName
)
Begin {
Write-Verbose "[$((Get-Date).TimeofDay) BEGIN ] Starting $($myinvocation.mycommand)"
$common = "Verbose", "Debug", "erroraction", "warningaction",
"informationaction", "errorvariable", "warningvariable", "informationvariable",
"outvariable", "outbuffer", "pipelinevariable"
} #begin
Process {
Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Getting parameter data for $Name "
$gcm = Get-Command -Name $name -ErrorAction Stop
if ($gcm.CommandType -eq 'alias') {
Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Resolving alias $Name "
$gcm = Get-Command -name $gcm.ResolvedCommandName
}
Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Getting parameters for $($gcm.name)"
$Params = $gcm.parameters
Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Filtering out common parameters"
foreach ($var in $common) {
$params.Remove($var) | Out-Null
}
$params.keys | foreach-object -Begin {
$resolved = @()
} -process {
$resolved += $gcm.ResolveParameter($_)
}
if ($ParameterName) {
foreach ($item in $ParameterName) {
$resolved.where( {$_.name -like $item})
}
}
else {
$resolved
}
} #process
End {
Write-Verbose "[$((Get-Date).TimeofDay) END ] Ending $($myinvocation.mycommand)"
} #end
} #close Get-CommandMetadata
Function Get-CommandMetadata {
[cmdletbinding()]
Param(
[Parameter(ValueFromPipeline, Mandatory, HelpMessage = "Enter the name of a command")]
[ValidateNotNullOrEmpty()]
[ValidateScript( {Get-Command $_})]
[string]$Name
)
Begin {
Write-Verbose "[$((Get-Date).TimeofDay) BEGIN ] Starting $($myinvocation.mycommand)"
} #begin
Process {
Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Getting command metadata for $Name "
$gcm = Get-Command -Name $name -ErrorAction Stop
#allow an alias or command name
if ($gcm.CommandType -eq 'Alias') {
$cmdName = $gcm.ResolvedCommandName
}
else {
$cmdName = $gcm.Name
}
New-Object System.Management.Automation.CommandMetaData $gcm
} #process
End {
Write-Verbose "[$((Get-Date).TimeofDay) END ] Ending $($myinvocation.mycommand)"
} #end
} #close Get-CommandMetadata
Function Copy-Command {
[cmdletbinding()]
Param(
[Parameter(Position = 0, Mandatory, HelpMessage = "Enter the name of a PowerShell command")]
[ValidateNotNullorEmpty()]
[string]$Command,
[Parameter(Position = 1, HelpMessage = "Enter the new name for your command using Verb-Noun convention")]
[ValidateNotNullorEmpty()]
[string]$NewName,
[switch]$IncludeDynamic,
[switch]$AsProxy,
[switch]$UseForwardHelp
)
Try {
Write-Verbose "[BEGIN ] Starting: $($MyInvocation.Mycommand)"
Write-Verbose "[BEGIN ] Getting command metadata for $command"
$gcm = Get-Command -Name $command -ErrorAction Stop
#allow an alias or command name
if ($gcm.CommandType -eq 'Alias') {
$cmdName = $gcm.ResolvedCommandName
}
else {
$cmdName = $gcm.Name
}
Write-Verbose "[BEGIN ] Resolved command to $cmdName"
$cmd = New-Object System.Management.Automation.CommandMetaData $gcm
}
Catch {
Write-Warning "Failed to create command metadata for $command"
Write-Warning $_.Exception.Message
}
if ($cmd) {
#create the metadata
if ($NewName) {
$Name = $NewName
}
else {
$Name = $cmd.Name
}
#define a metadata comment block
$myComment = @"
<#
This is a copy of:
$(($gcm | Format-Table -AutoSize | Out-String).trim())
Created: $('{0:dd} {0:y}' -f (get-date))
Author : $env:username
#>
"@
#define the beginning of text for the new command
#dynamically insert the command's module if one exists
$text = @"
#requires -version $(([regex]"\d+\.\d+").match($psversiontable.psversion).value)
$(if ($gcm.modulename -AND $gcm.modulename -notmatch "Microsoft\.PowerShell\.\w+") { "#requires -module $($gcm.modulename)" })
$myComment
Function $Name {
"@
#manually copy parameters from original command if param block not found
#this can happen with dynamic parameters like those in the AD cmdlets
if (-Not [System.Management.Automation.ProxyCommand]::GetParamBlock($gcm)) {
Write-Verbose "[PROCESS] No param block detected. Looking for dynamic parameters"
$IncludeDynamic = $True
}
if ($IncludeDynamic) {
Write-Verbose "[PROCESS] Adding dynamic parameters"
$params = $gcm.parameters.GetEnumerator() | where-object { $_.value.IsDynamic}
foreach ($p in $params) {
$cmd.Parameters.add($p.key, $p.value)
}
}
if ($UseForwardHelp) {
#define a regex to pull forward help from a proxy command
[regex]$rx = "\.ForwardHelp.*\s+\.ForwardHelp.*"
Write-Verbose "[PROCESS] Using forwarded help"
$help = $rx.match([System.Management.Automation.ProxyCommand]::Create($cmd)).Value
}
else {
#if not using the default Forwardhelp links, get comment based help instead
#get help as a comment block
$help = [System.Management.Automation.ProxyCommand]::GetHelpComments((get-help $Command))
#substitute command name
$help = $help -replace $Command, $NewName
#remove help link
$cmd.HelpUri = $null
}
Write-Verbose "[PROCESS] Adding Help"
$Text += @"
<#
$help
#>
"@
#cmdletbinding
$Text += [System.Management.Automation.ProxyCommand]::GetCmdletBindingAttribute($cmd)
#get parameters
$NewParameters = [System.Management.Automation.ProxyCommand]::GetParamBlock($cmd)
Write-Verbose "[PROCESS] Cleaning up parameter names"
[regex]$rx = '\]\r\s+\${(?<var>\w+)}'
#replace the {variable-name} with just variable-name and joined to type name
$NewParameters = $rx.Replace($NewParameters, ']$$${var}')
#Insert parameters
$Text += @"
Param(
$NewParameters
)
Begin {
Write-Verbose "[BEGIN ] Starting `$(`$MyInvocation.Mycommand)"
Write-Verbose "[BEGIN ] Using parameter set `$(`$PSCmdlet.ParameterSetName)"
Write-Verbose (`$PSBoundParameters | Out-String)
"@
Write-Verbose "[PROCESS] Adding Begin block"
if ($AsProxy) {
$Text += [System.Management.Automation.ProxyCommand]::GetBegin($cmd)
}
$Text += @"
} #begin
Process {
"@
Write-Verbose "[PROCESS] Adding Process block"
if ($AsProxy) {
$Text += [System.Management.Automation.ProxyCommand]::GetProcess($cmd)
}
else {
$Text += @"
$($cmd.name) @PSBoundParameters
"@
}
$Text += @"
} #process
End {
Write-Verbose "[END ] Ending `$(`$MyInvocation.Mycommand)"
"@
Write-Verbose "[PROCESS] Adding End block"
If ($AsProxy) {
$Text += [System.Management.Automation.ProxyCommand]::GetEnd($cmd)
}
$Text += @"
} #end
"@
#insert closing text
$Text += @"
} #end function $Name
"@
if ($host.Name -match "PowerShell ISE") {
#open in a new ISE tab
$tab = $psise.CurrentPowerShellTab.Files.Add()
Write-Verbose "[END ] Opening new command in a new ISE tab"
$tab.editor.InsertText($Text)
#jump to the top
$tab.Editor.SetCaretPosition(1, 1)
}
elseif ($host.name -eq 'Visual Studio Code Host') {
$pseditor.workspace.newfile()
$pseditor.GetEditorContext().currentfile.insertText($text)
}
else {
#just write the new command to the pipeline
$Text
}
}
Write-Verbose "[END ] $($MyInvocation.MyCommand)"
}#end Copy-Command