forked from alx9r/ToolFoundations
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmdlet.ps1
541 lines (472 loc) · 15.9 KB
/
cmdlet.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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
Set-Alias gbpm Get-BoundParams
Set-Alias gcp Get-CommonParams
Set-Alias '>>' ConvertTo-ParamObject
Set-Alias icms Invoke-CommandSafely
Function Get-BoundParams
{
<#
.SYNOPSIS
A terse and universal way to get the cmdlet's bound parameters.
.DESCRIPTION
The alias gbpm for Get-BoundParams can be use to obtain the current cmdlet's bound parameters in a terse manner whose value is available even from debuggers. Get-BoundParams allows for this terse alternative to $PSCmdlet.MyInvocation.BoundParameters:
&(gbpm)
A test for the existence of a parameter in an advanced function then becomes the following:
if ( (&(gbpm)).Keys -contains 'SomeParameter' )
You might also consider $PSBoundParameters which is somewhat terser than $PSCmdlet.MyInvocation.BoundParameters but is not available from debuggers (see about_Debuggers and https://stackoverflow.com/q/9025942/1404637).
.OUTPUTS
A scriptblock that evaluates to the cmdlet's bound parameters.
.EXAMPLE
function f1 {
[CmdletBinding()]
param($p1)
process
{
if
(
(&(gbpm)).Keys -contains 'p1' -and # tests existence of parameter
-not $p1 # tests value of parameter
)
{
Write-Host 'p1 provided, but false'
}
}
}
f1 -p1 $false
This demonstrates the difference between testing the value and testing the existence of a parameter. Get-BoundParams streamlines testing for existence of parameters.
.LINK
about_Debuggers
https://stackoverflow.com/q/9025942/1404637
#>
[CmdletBinding()]
param
(
# Get-BoundParams normally only provides user-defined parameters. Set this switch to include common parameters.
[switch]
[Alias('cp')]
$IncludeCommonParameters,
# Get-BoundParams normally returns a scriptblock. Set this switch to return the code string used to create the scriptblock, instead.
[switch]
$Code
)
process
{
if ( $IncludeCommonParameters )
{
$codeString = "iex '`$PSCmdlet.MyInvocation.BoundParameters'"
}
else
{
$codeString = @'
$cp = [System.Management.Automation.PSCmdlet]::CommonParameters
$bp = iex "`$PSCmdlet.MyInvocation.BoundParameters"
$ncbp = @{}
$bp.Keys |
? { $cp -notContains $_ } |
% {
$ncbp[$_] = $bp[$_]
}
$ncbp
'@
}
if ($Code) { return $codeString }
[scriptblock]::Create($codeString)
}
}
Function Get-CommonParams
{
<#
.SYNOPSIS
A terse way to get cascade common parameters from one cmdlet to another.
.DESCRIPTION
The alias gcp for Get-CommonParams can be use to cascade the parameters that control output streams from one cmdlet to another. Get-CommonParams allows for this terse usage:
$cp = &(gcp)
Invoke-SomeOtherFunction @cp
.OUTPUTS
A scriptblock that evaluates to the hashtable that, when passed as splat parameters to another cmdlet, cascades the common parameters of the calling cmdlet to that cmdlet.
.EXAMPLE
function f1 {
[CmdletBinding()]
param()
process
{
$cp = &(gcp)
f2 @cp
}
}
function f2 {
[CmdletBinding()]
param()
process
{
Write-Verbose 'This gets output to the Verbose stream.'
}
}
f1 -Verbose
This demonstrates how to use Get-CommonParams to cascade the value and existence of the Verbose switch from cmdlet f1 to cmdlet f2.
#>
[CmdletBinding()]
param
(
# The list of output stream parameters to cascade
[parameter(ValueFromPipeline = $true,
Position = 1,
ValueFromPipelineByPropertyName = $true)]
[ValidateNotNullOrEmpty()]
[string[]]
$ParamList = ('Debug','ErrorAction','ErrorVariable','Verbose',
'WarningAction','WarningVariable','WhatIf','Confirm'),
# Get-CommonParams normally returns a scriptblock. Set this switch to return the code string used to create the scriptblock, instead.
[switch]
$Code
)
process
{
$commonParameters = Get-CommonParameterNames
if ( (&(gbpm)).Keys -contains 'ParamList' )
{
$pl = $ParamList
}
else
{
$pl = Get-CommonParameterNames
}
# get the valid output stream names
$vcp = $pl |
% {
if ( $commonParameters -Contains $_ ) { $_ }
else
{
Write-Error "`"$_`" is not a valid Common Parameter."
}
}
$codeString = @'
$hash = @{}
'@
foreach ($name in $vcp)
{
$codeString = $codeString + @"
if ( `$PSCmdlet.MyInvocation.BoundParameters.Keys -Contains '$name' )
{
`$hash['$name'] = `$PSCmdlet.MyInvocation.BoundParameters['$name']
}
"@
}
$codeString = $codeString + @'
$hash
'@
if ( $Code ) { return $codeString }
[scriptblock]::Create($codeString)
}
}
function NoParams
{
[CmdletBinding()]
param()
process{}
}
Function Get-CommonParameterNames
{
[CmdletBinding()]
param()
process
{
if ( $PSVersionTable.PSVersion.Major -gt 3 )
{
[System.Management.Automation.PSCmdlet]::CommonParameters+`
[System.Management.Automation.PSCmdlet]::OptionalCommonParameters
}
else
{
(Get-Command NoParams).Parameters.Keys
}
}
}
function Publish-Failure
{
<#
.SYNOPSIS
A DRY way to implement user-selectable failure actions.
.DESCRIPTION
Publish-Failure throws an exception, reports an error, or a verbose message depending on ErrorActionPrefernce. This allows implementation of Cmdlets that vary their failure actions without repeating code. For example, Test-ValidFileName is used in two different ways:
1. Publicly to test whether a file name is valid. In this case the user doesn't expect an exception to be thrown if the test fails.
2. Internally to assert that a file name is valid. In this case the calling function needs Test-ValidFileName to throw an exception with the detailed reasons for failure, so that the user of the calling function sees the underlying reason for the failure.
Publish-Failure allows both of the above needs to be fulfilled on a single line of code without repetition. Here is an example:
function Do-Something
{
param($FileName)
$FileName | Test-ValidFilename -ErrorAction Stop
...
}
Normally Test-ValidFilename returns false on a failure. However, that behavior would violate one of Scott Hanselman's rules of thumbs for Do-Something:
"If your functions are named well,
using verbs (actions) and nouns
(stuff to take action on) then
throw an exception if your method
can't do what it says it can."
Accordingly, we need a failure of Test-ValidFilename to throw an exception rather than just silently continue. Because we want that exception to contain detailed information about the cause of the failure, Test-ValidFilename's fail behavior needs to be changed to throw using -ErrorAction Stop. This variability is implemented by Test-ValidFilename by calling Publish-Failure. Look at the implementation of Test-ValidFilename for an example.
.OUTPUTS
A scriptblock that can be invoked by the caller to publish the failure according to the parameters. The scriptblock will either contain code that throws an exception, calls Write-Error, or Write-Verbose.
.LINK
http://www.hanselman.com/blog/GoodExceptionManagementRulesOfThumb.aspx
Test-ValidFileName
#>
[CmdletBinding()]
param
(
# The list of arguments for the exception when ErrorAction is Stop. The first element is used as the message when ErrorAction is Continue or SilentlyContinue.
[Parameter(Mandatory = $true,
Position = 1,
ValueFromPipelineByPropertyName = $true)]
[string[]]
$ArgumentList='Unspecified Error',
# the type of exception to throw for ErrorAction Stop
[Parameter(Position = 2,
ValueFromPipelineByPropertyName = $true)]
[Type]
$ExceptionType=[System.Exception],
# By default, output is Verbose when ErrorAction is Continue. Use this switch to Write-Error when ErrorAction is Continue.
[switch]
$AllowError,
# output the resulting scriptblock as code instead
[switch]
$AsCode
)
process
{
if (-not $PSBoundParameters.ContainsKey('ErrorActionPreference'))
{
$ErrorActionPreference = $PSCmdlet.GetVariableValue('ErrorActionPreference')
}
switch ($ErrorActionPreference) {
'Continue' {
if ( $AllowError )
{
$code = "Write-Error '$($ArgumentList[0])'"
}
else
{
$code = "Write-Verbose '$($ArgumentList[0])'"
}
}
'SilentlyContinue' {
$code = "Write-Verbose '$($ArgumentList[0])'"
}
'Stop' {
$argumentListString = ConvertTo-PsLiteralString $ArgumentList
$code = "throw New-Object -TypeName $ExceptionType -ArgumentList $argumentListString"
}
}
if ( $AsCode )
{
return $code
}
return [scriptblock]::Create($code)
}
}
Function ConvertTo-ParamObject
{
[CmdletBinding()]
param
(
[parameter(Position = 1,
Mandatory = $true,
ValueFromPipeline = $true)]
[AllowNull()]
$InputObject
)
process
{
if ( $null -eq $InputObject )
{
return
}
if
(
# the usual type of splat parameters
$InputObject -is [hashtable] -or
# the type of PSBoundParameters
([string]$InputObject.GetType()) -eq 'System.Collections.Generic.Dictionary[string,System.Object]'
)
{
return New-Object psobject -Property $InputObject
}
return $InputObject
}
}
if ( $PSVersionTable.PSVersion.Major -ge 4)
{
function Get-Parameters
{
[CmdletBinding()]
param
(
[Parameter(Position = 1,
Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true)]
[string]
$CmdletName,
[Parameter(Position = 2,
ValueFromPipelineByPropertyName = $true)]
[string]
$ParameterSetName,
[Parameter(Position = 3,
ValueFromPipelineByPropertyName = $true)]
[ValidateSet('Required','All')]
[string]
$Mode='All'
)
process
{
$bp = &(gbpm)
$cmd = Get-Command $CmdletName -ErrorAction Stop
if
(
$bp.Keys -notcontains 'ParameterSetName' -and
$cmd.ParameterSets.Count -gt 1 -and
-not $cmd.DefaultParameterSet
)
{
throw New-Object System.ArgumentException(
"Cmdlet $CmdletName has more than one parameterset and no default. You must provide ParameterSetName.",
'ParameterSetName'
)
}
if
(
$bp.Keys -contains 'ParameterSetName' -and
($cmd.ParameterSets | % {$_.Name}) -notcontains $ParameterSetName
)
{
throw New-Object System.ArgumentException(
"Cmdlet $CmdletName does not have ParameterSetName $ParameterSetName.",
'ParameterSetName'
)
}
if ( -not ($cmd.Parameters.Keys | ? { (Get-CommonParameterNames) -notcontains $_}))
{
return
}
if
(
$bp.Keys -notcontains 'ParameterSetName' -and
$cmd.DefaultParameterSet
)
{
$psn = $cmd.DefaultParameterSet
}
if
(
$bp.Keys -notcontains 'ParameterSetName' -and
-not $cmd.DefaultParameterSet
)
{
$psn = $cmd.ParameterSets[0].Name
}
if
(
$bp.Keys -contains 'ParameterSetName'
)
{
$psn = $ParameterSetName
}
$parameterSet = $cmd.ParameterSets | ? { $_.Name -eq $psn }
$parameterSetParameterNames = $parameterSet.Parameters |
? { (Get-CommonParameterNames) -notcontains $_.Name } |
% {$_.Name}
$help = Get-Help $CmdletName
return $help.parameters.parameter |
? {
(
$_.Required -eq $true -or
$Mode -eq 'All'
) -and
$parameterSetParameterNames -contains $_.Name
} |
% {$_.Name}
}
}
function Test-ValidParams
{
[CmdletBinding()]
param
(
[Parameter(Position = 1,
Mandatory = $true,
ValueFromPipelineByPropertyName = $true)]
[string]
$CmdletName,
[Parameter(Position = 2,
Mandatory = $true,
ValueFromPipelineByPropertyName = $true)]
[hashtable]
$SplatParams,
[Parameter(Position = 3,
ValueFromPipelineByPropertyName = $true)]
[string]
$ParameterSetName
)
process
{
foreach ( $requiredParam in (&(gbpm) | >> | Get-Parameters -Mode Required) )
{
if ( $SplatParams.Keys -notcontains $requiredParam )
{
$message = "Required parameter $requiredParam not in SplatParams for Cmdlet $CmdletName"
$param = $requiredParam
}
}
$allParams = (&(gbpm) | >> | Get-Parameters -Mode All)
foreach ( $splatParam in $SplatParams.Keys )
{
if ( $allParams -notcontains $splatParam )
{
$message = "SplatParam $splatParam provided but not a parameter of Cmdlet $CmdletName"
$param = $splatParam
}
}
if ($message)
{
Switch ($ErrorActionPreference) {
'Stop' {
throw New-Object System.ArgumentException(
$message,
$param
)
}
'Continue' { Write-Error $message}
'SilentlyContinue' { Write-Verbose $message }
}
return $false
}
return $true
}
}
function Invoke-CommandSafely
{
[CmdletBinding()]
param
(
[Parameter(Position = 1,
Mandatory = $true,
ValueFromPipelineByPropertyName = $true)]
[string]
$CmdletName,
[Parameter(Position = 2,
Mandatory = $true,
ValueFromPipelineByPropertyName = $true)]
[hashtable]
$SplatParams,
[Parameter(Position = 3,
ValueFromPipelineByPropertyName = $true)]
[string]
$ParameterSetName
)
process
{
$bp = &(gbpm)
Test-ValidParams @bp -ErrorAction Stop | Out-Null
& $CmdletName @SplatParams
}
}
}