-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathModuleBuild.psm1
More file actions
2061 lines (1786 loc) · 82.7 KB
/
ModuleBuild.psm1
File metadata and controls
2061 lines (1786 loc) · 82.7 KB
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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
## Pre-Loaded Module code ##
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseDeclaredVarsMoreThanAssignments", "ModuleBuildLoggingEnabled",Justification="ModuleBuildLoggingEnabled is optional. It's used to enable Nlog-based logging.")]
param()
$ModuleBuildLoggingEnabled = $false # Set to true to enable nlog-based logging
## PRIVATE MODULE FUNCTIONS AND DATA ##
Function Add-MBMissingCBH {
<#
.SYNOPSIS
Create comment based help for a function.
.DESCRIPTION
Create comment based help for a function.
.PARAMETER Code
Multi-line or piped lines of code to process.
.EXAMPLE
PS > $test = Get-Content 'C:\temp\test.ps1' -raw
PS > $test | Add-MBMissingCBH | clip
Takes C:\temp\test.ps1 as input, creates basic comment based help and puts the result in the clipboard
to be pasted elsewhere for review.
.NOTES
Author: Zachary Loeber
Site: http://www.the-little-things.net/
Requires: Powershell 3.0
Version History
1.0.0 - Initial release
1.0.1 - Updated for ModuleBuild
#>
[CmdletBinding()]
param(
[parameter(Position=0, ValueFromPipeline=$true, HelpMessage='Lines of code to process.')]
[string[]]$Code
)
begin {
# CBH pattern that tells us CBH likely already exists
$CBHPattern = "(?ms)(^\s*\<#.*[\.SYNOPSIS|\.DESCRIPTION|\.PARAMETER|\.EXAMPLE|\.NOTES|\.LINK].*?#>)"
$Codeblock = @()
}
process {
$Codeblock += $Code
}
end {
$ScriptText = ($Codeblock | Out-String).trim("`r`n")
# If no sign of CBH exists then try to generate and insert it
if ($ScriptText -notmatch $CBHPattern) {
$CBH = @($ScriptText | New-MBCommentBasedHelp)
if ($CBH.Count -gt 1) {
throw 'Too many functions are defined in the input string!'
}
if ($CBH.Count -ne 0) {
try {
$currscriptblock = [scriptblock]::Create($ScriptText)
. $currscriptblock
$currfunct = get-command $CBH.FunctionName
}
catch {
throw $_
}
$UpdatedFunct = 'Function ' + $currfunct.Name + ' {' + "`r`n" + $CBH.CBH + "`r`n" + $currfunct.definition + "`r`n" + '}'
$UpdatedFunct
}
else {
Write-Warning 'Unable to generate CBH for the script text!'
$ScriptText
}
}
else {
Write-Verbose "Comment based help already exists - skipping CBH insertion and returning original script."
$ScriptText
}
}
}
function Convert-MBArrayToRegex {
# Takes an array of strings and turns it into a regex matchable string
[CmdletBinding()]
param(
[parameter(Position = 0, ValueFromPipeline = $TRUE)]
[String[]]$Item,
[parameter(Position = 1)]
[Switch]$DoNotEscape
)
begin {
$Items = @()
}
process {
$Items += $Item
}
end {
if ($Items.Count -gt 0) {
if ($DoNotEscape) {
'^(' + ($Items -join '|') + ')$'
}
else {
'^(' + (($Items | ForEach-Object{[regex]::Escape($_)}) -join '|') + ')$'
}
}
else {
'^()$'
}
}
}
function Get-CallerPreference {
<#
.Synopsis
Fetches "Preference" variable values from the caller's scope.
.DESCRIPTION
Script module functions do not automatically inherit their caller's variables, but they can be
obtained through the $PSCmdlet variable in Advanced Functions. This function is a helper function
for any script module Advanced Function; by passing in the values of $ExecutionContext.SessionState
and $PSCmdlet, Get-CallerPreference will set the caller's preference variables locally.
.PARAMETER Cmdlet
The $PSCmdlet object from a script module Advanced Function.
.PARAMETER SessionState
The $ExecutionContext.SessionState object from a script module Advanced Function. This is how the
Get-CallerPreference function sets variables in its callers' scope, even if that caller is in a different
script module.
.PARAMETER Name
Optional array of parameter names to retrieve from the caller's scope. Default is to retrieve all
Preference variables as defined in the about_Preference_Variables help file (as of PowerShell 4.0)
This parameter may also specify names of variables that are not in the about_Preference_Variables
help file, and the function will retrieve and set those as well.
.EXAMPLE
Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
Imports the default PowerShell preference variables from the caller into the local scope.
.EXAMPLE
Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState -Name 'ErrorActionPreference','SomeOtherVariable'
Imports only the ErrorActionPreference and SomeOtherVariable variables into the local scope.
.EXAMPLE
'ErrorActionPreference','SomeOtherVariable' | Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
Same as Example 2, but sends variable names to the Name parameter via pipeline input.
.INPUTS
String
.OUTPUTS
None. This function does not produce pipeline output.
.LINK
about_Preference_Variables
#>
[CmdletBinding(DefaultParameterSetName = 'AllVariables')]
param (
[Parameter(Mandatory = $true)]
[ValidateScript({ $_.GetType().FullName -eq 'System.Management.Automation.PSScriptCmdlet' })]
$Cmdlet,
[Parameter(Mandatory = $true)]
[System.Management.Automation.SessionState]$SessionState,
[Parameter(ParameterSetName = 'Filtered', ValueFromPipeline = $true)]
[string[]]$Name
)
begin {
$filterHash = @{}
}
process {
if ($null -ne $Name)
{
foreach ($string in $Name)
{
$filterHash[$string] = $true
}
}
}
end {
# List of preference variables taken from the about_Preference_Variables help file in PowerShell version 4.0
$vars = @{
'ErrorView' = $null
'FormatEnumerationLimit' = $null
'LogCommandHealthEvent' = $null
'LogCommandLifecycleEvent' = $null
'LogEngineHealthEvent' = $null
'LogEngineLifecycleEvent' = $null
'LogProviderHealthEvent' = $null
'LogProviderLifecycleEvent' = $null
'MaximumAliasCount' = $null
'MaximumDriveCount' = $null
'MaximumErrorCount' = $null
'MaximumFunctionCount' = $null
'MaximumHistoryCount' = $null
'MaximumVariableCount' = $null
'OFS' = $null
'OutputEncoding' = $null
'ProgressPreference' = $null
'PSDefaultParameterValues' = $null
'PSEmailServer' = $null
'PSModuleAutoLoadingPreference' = $null
'PSSessionApplicationName' = $null
'PSSessionConfigurationName' = $null
'PSSessionOption' = $null
'ErrorActionPreference' = 'ErrorAction'
'DebugPreference' = 'Debug'
'ConfirmPreference' = 'Confirm'
'WhatIfPreference' = 'WhatIf'
'VerbosePreference' = 'Verbose'
'WarningPreference' = 'WarningAction'
}
foreach ($entry in $vars.GetEnumerator()) {
if (([string]::IsNullOrEmpty($entry.Value) -or -not $Cmdlet.MyInvocation.BoundParameters.ContainsKey($entry.Value)) -and
($PSCmdlet.ParameterSetName -eq 'AllVariables' -or $filterHash.ContainsKey($entry.Name))) {
$variable = $Cmdlet.SessionState.PSVariable.Get($entry.Key)
if ($null -ne $variable) {
if ($SessionState -eq $ExecutionContext.SessionState) {
Set-Variable -Scope 1 -Name $variable.Name -Value $variable.Value -Force -Confirm:$false -WhatIf:$false
}
else {
$SessionState.PSVariable.Set($variable.Name, $variable.Value)
}
}
}
}
if ($PSCmdlet.ParameterSetName -eq 'Filtered') {
foreach ($varName in $filterHash.Keys) {
if (-not $vars.ContainsKey($varName)) {
$variable = $Cmdlet.SessionState.PSVariable.Get($varName)
if ($null -ne $variable)
{
if ($SessionState -eq $ExecutionContext.SessionState)
{
Set-Variable -Scope 1 -Name $variable.Name -Value $variable.Value -Force -Confirm:$false -WhatIf:$false
}
else
{
$SessionState.PSVariable.Set($variable.Name, $variable.Value)
}
}
}
}
}
}
}
function Get-MBCommonParameter {
# Helper function to get all the automatically added parameters in an
# advanced function
function somefunct {
[CmdletBinding(SupportsShouldProcess = $true, SupportsPaging = $true, SupportsTransactions = $true)]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSShouldProcess", "", Scope="Function", Target="somefunct",Justification="This is a dummy function in order to get all CommonParameters without hardcoding them. There is no reason for it to actually use SupportsShouldProcess.")]
param()
}
((Get-Command somefunct).Parameters).Keys
}
function Get-MBFunction {
<#
.SYNOPSIS
Enumerates all functions within lines of code.
.DESCRIPTION
Enumerates all functions within lines of code.
.PARAMETER Code
Multiline or piped lines of code to process.
.PARAMETER Name
Name of a function to return. Default is all functions.
.EXAMPLE
TBD
.NOTES
Author: Zachary Loeber
Site: http://www.the-little-things.net/
Requires: Powershell 3.0
Version History
1.0.0 - Initial release
.LINK
http://www.the-little-things.net
#>
[CmdletBinding()]
param(
[parameter(Position = 0, Mandatory = $true, ValueFromPipeline=$true, HelpMessage='Lines of code to process.')]
[AllowEmptyString()]
[string[]]$Code,
[parameter(Position=1, HelpMessage='Name of function to process.')]
[string]$Name = '*'
)
begin {
$ThisFunc = $MyInvocation.MyCommand.Name
Write-Verbose "$($ThisFunc): Begin."
$Codeblock = @()
$ParseError = $null
$Tokens = $null
$predicate = {
($args[0] -is [System.Management.Automation.Language.FunctionDefinitionAst]) -and
($args[0].Name -like $name)
}
}
process {
$Codeblock += $Code
}
end {
$ScriptText = ($Codeblock | Out-String).trim("`r`n")
Write-Verbose "$($ThisFunc): Attempting to parse AST."
$AST = [System.Management.Automation.Language.Parser]::ParseInput($ScriptText, [ref]$Tokens, [ref]$ParseError)
if($ParseError) {
throw "$($ThisFunc): Will not work properly with errors in the script, please modify based on the above errors and retry."
}
# First get all blocks
$Blocks = $AST.FindAll($predicate, $true)
Foreach ($Block in $Blocks) {
$FunctionProps = @{
Name = $Block.Name
Definition = $Block.Extent.Text
IsEmbedded = $false
AST = $Block
}
if (@(Get-MBParentASTType $Block) -contains 'FunctionDefinitionAst') {
$FunctionProps.IsEmbedded = $true
}
New-Object -TypeName psobject -Property $FunctionProps
}
Write-Verbose "$($ThisFunc): End."
}
}
function Get-MBTFunctionParameter {
<#
.SYNOPSIS
Return all parameters for each function found in a code block.
.DESCRIPTION
Return all parameters for each function found in a code block.
.PARAMETER Code
Multi-line or piped lines of code to process.
.PARAMETER Name
Name of fuction to process. If no funciton is given first the entire script will be processed for general parameters. If none are found every function in the script will be processed.
.PARAMETER ScriptParameters
Parse for script parameters only.
.PARAMETER IncludeEmbedded
Include functions within other functions.
.EXAMPLE
PS > $testfile = 'C:\temp\test.ps1'
PS > $test = Get-Content $testfile -raw
PS > $test | Get-MBTFunctionParameter -ScriptParameters
Takes C:\temp\test.ps1 as input, gathers any script's parameters and prints the output to the screen.
.NOTES
This will return every parameter of every parameter set. This means you could get far more parameters than you expect.
Author: Zachary Loeber
Site: http://www.the-little-things.net/
Requires: Powershell 3.0
Version History
1.0.0 - Initial release
1.0.1 - Updated function name to remove plural format
Added Name parameter and logic for getting script parameters if no function is defined.
Added ScriptParameters parameter to include parameters for a script (not just ones associated with defined functions)
1.0.2 - Added SuppressMessageAttribute for functionpredicate
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseDeclaredVarsMoreThanAssignments","functionpredicate",Scope="Function",Target='Get-MBTFunctionParameter',Justification="Unused AST filter")]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseDeclaredVarsMoreThanAssignments","CommonParams",Scope="Function",Target='Get-MBTFunctionParameter',Justification="")]
[CmdletBinding()]
param(
[parameter(ValueFromPipeline=$true, HelpMessage='Lines of code to process.')]
[string[]]$Code,
[parameter(Position=1, HelpMessage='Name of function to process.')]
[string]$Name = '*',
[parameter(Position=2, HelpMessage='Try to parse for top-level/non-function script parameters as well.')]
[switch]$ScriptParameters,
[parameter(Position=3, HelpMessage='Include parameters and functions of embedded functions.')]
[switch]$IncludeEmbedded
)
begin {
$FunctionName = $MyInvocation.MyCommand.Name
Write-Verbose "$($FunctionName): Begin."
$Codeblock = @()
$ParseError = $null
$Tokens = $null
$functionpredicate = {
($args[0] -is [System.Management.Automation.Language.FunctionDefinitionAst]) -and
($args[0].Name -like $name)
}
$parampredicate = { ($args[0] -is [System.Management.Automation.Language.ParameterAst]) }
$typepredicate = { ($args[0] -is [System.Management.Automation.Language.TypeConstraintAst]) }
$paramattributes = { ($args[0] -is [System.Management.Automation.Language.NamedAttributeArgumentAst]) }
$output = @()
}
process {
$Codeblock += $Code
$CommonParams = Get-MBCommonParameter
}
end {
$ScriptText = ($Codeblock | Out-String).trim("`r`n")
Write-Verbose "$($FunctionName): Attempting to parse AST."
$AST = [System.Management.Automation.Language.Parser]::ParseInput($ScriptText, [ref]$Tokens, [ref]$ParseError)
if($ParseError) {
throw "$($FunctionName): Will not work properly with errors in the script, please modify based on the above errors and retry."
}
if (-not $ScriptParameters) {
$functions = $CodeBlock | Get-MBFunction -Name $Name
if (-not $IncludeEmbedded) {
Write-Verbose "$($FunctionName): Not including embedded functions."
$functions = $functions | Where-Object {-not $_.IsEmbedded}
}
If([string]::IsNullOrEmpty($functions))
{
Write-Verbose "$($FunctionName): There were no script parameters found"
} else
{
Foreach ($f in $functions) {
$function = $f.ast
$Parameters = $function.FindAll($parampredicate, $true)
foreach ($p in $Parameters) {
$ParamType = $p.FindAll($typepredicate, $true)
Write-Verbose "$($FunctionName): Processing Parameter of type [$($ParamType.typeName.FullName)] - $($p.Name.VariablePath.ToString())"
$OutProps = @{
'FunctionName' = $function.Name.ToString()
'ParameterName' = $p.Name.VariablePath.ToString()
'ParameterType' = $ParamType[0].typeName.FullName
}
# This will add in any other parameter attributes if they are specified (default attributes are thus not included and output may not be normalized)
$p.FindAll($paramattributes, $true) | ForEach-Object {
$OutProps.($_.ArgumentName) = $_.Argument.Value
}
$Output += New-Object -TypeName PSObject -Property $OutProps
}
}
}
}
else {
Write-Verbose "$($FunctionName): Processing Script parameters"
if ($ast.ParamBlock -ne $null) {
$scriptparams = $ast.ParamBlock
$Parameters = $scriptparams.FindAll($parampredicate, $true)
foreach ($p in $Parameters) {
$ParamType = $p.FindAll($typepredicate, $true)
Write-Verbose "$($FunctionName): Processing Parameter of type [$($ParamType.typeName.FullName)] - $($p.Name.VariablePath.ToString())"
$OutProps = @{
'FunctionName' = 'Script'
'ParameterName' = $p.Name.VariablePath.ToString()
'ParameterType' = $ParamType[0].typeName.FullName
}
# This will add in any other parameter attributes if they are specified (default attributes are thus not included and output may not be normalized)
$p.FindAll($paramattributes, $true) | ForEach-Object {
$OutProps.($_.ArgumentName) = $_.Argument.Value
}
$Output += New-Object -TypeName PSObject -Property $OutProps
}
}
else {
Write-Verbose "$($FunctionName): There were no script parameters found"
}
}
$Output
Write-Verbose "$($FunctionName): End."
}
}
function Get-MBParentASTType {
<#
.SYNOPSIS
Retrieves all parent types of a given AST element.
.DESCRIPTION
.PARAMETER Code
Multiline or piped lines of code to process.
.EXAMPLE
Description
-----------
.NOTES
Author: Zachary Loeber
Site: http://www.the-little-things.net/
Requires: Powershell 3.0
Version History
1.0.0 - Initial release
#>
[CmdletBinding()]
param(
[parameter(Position = 0, Mandatory = $true, ValueFromPipeline=$true, HelpMessage='AST element to process.')]
$AST
)
# Pull in all the caller verbose,debug,info,warn and other preferences
if ($script:ThisModuleLoaded -eq $true) { Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState }
$FunctionName = $MyInvocation.MyCommand.Name
Write-Verbose "$($FunctionName): Begin."
$ASTParents = @()
if ($AST.Parent -ne $null) {
$CurrentParent = $AST.Parent
$KeepProcessing = $true
}
else {
$KeepProcessing = $false
}
while ($KeepProcessing) {
$ASTParents += $CurrentParent.GetType().Name.ToString()
if ($CurrentParent.Parent -ne $null) {
$CurrentParent = $CurrentParent.Parent
$KeepProcessing = $true
}
else {
$KeepProcessing = $false
}
}
$ASTParents
Write-Verbose "$($FunctionName): End."
}
function New-MBCommentBasedHelp {
<#
.SYNOPSIS
Create comment based help for functions within a given scriptblock.
.DESCRIPTION
Create comment based help for functions within a given scriptblock.
.PARAMETER Code
Multi-line or piped lines of code to process.
.PARAMETER ScriptParameters
Process the script parameters as the source of the comment based help.
.EXAMPLE
PS > $testfile = 'C:\temp\test.ps1'
PS > $test = Get-Content $testfile -raw
PS > $test | New-MBCommentBasedHelp | clip
Takes C:\temp\test.ps1 as input, creates basic comment based help and puts the result in the clipboard
to be pasted elsewhere for review.
.EXAMPLE
PS > $CBH = Get-Content 'C:\EWSModule\Get-EWSContact.ps1' -Raw | New-MBTommentBasedHelp -Verbose
PS > ($CBH | Where {$FunctionName -eq 'Get-EWSContact'}).CBH
Consumes Get-EWSContact.ps1 and generates advanced CBH templates for all functions found within. Print out to the screen the advanced
CBH for just the Get-EWSContact function.
.NOTES
Author: Zachary Loeber
Site: http://www.the-little-things.net/
Requires: Powershell 3.0
Version History
1.0.0 - Initial release
1.0.1 - Updated for ModuleBuild
1.0.2 - Added SuppressMessageAttribute
1.0.3 - Extra Verbose message to check if function had Params
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseDeclaredVarsMoreThanAssignments", "ScriptText",Scope="Function",Target="New-MBCommentBasedHelp",Justification="Seems it's here since duo a copy paste from other functions (Add-MBMissingCBH,Get-MBFunction,Get-MBTFunctionParameter). Leaving it here since it doesn't do any harm.")]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions","",Scope="Function",Target="New-MBCommentBasedHelp",Justification="Function does not change system state. Simply outputs a obj with CommentBasedHelp.")]
[CmdletBinding()]
param(
[parameter(Position=0, ValueFromPipeline=$true, HelpMessage='Lines of code to process.')]
[string[]]$Code,
[parameter(Position=1, HelpMessage='Process the script parameters as the source of the comment based help.')]
[switch]$ScriptParameters
)
begin {
$FunctionName = $MyInvocation.MyCommand.Name
Write-Verbose "$($FunctionName): Begin."
$CBH_PARAM = @'
.PARAMETER %%PARAM%%
%%PARAMHELP%%
'@
$Codeblock = @()
$CBHTemplate = @'
<#
.SYNOPSIS
TBD
.DESCRIPTION
TBD
%%PARAMETER%% .EXAMPLE
TBD
#>
'@
}
process {
$Codeblock += $Code
}
end {
$ScriptText = ($Codeblock | Out-String).trim("`r`n")
Write-Verbose "$($FunctionName): Attempting to parse parameters."
$FuncParams = @{}
if ($ScriptParameters) {
$FuncParams.ScriptParameters = $true
}
$AllParams = Get-MBTFunctionParameter @FuncParams -Code $Codeblock | Sort-Object -Property FunctionName
$AllFunctions = @($AllParams.FunctionName | Select-Object -unique)
If([string]::IsNullOrEmpty($AllFunctions))
{
Write-Verbose "$($FunctionName): Found no Params in function."
} else
{
foreach ($f in $AllFunctions) {
$OutCBH = @{}
$OutCBH.FunctionName = $f
[string]$OutParams = ''
$fparams = @($AllParams | Where-Object {$_.FunctionName -eq $f} | Sort-Object -Property Position)
if ($fparams.count -gt 0) {
$fparams | ForEach-Object {
$ParamHelpMessage = if ([string]::IsNullOrEmpty($_.HelpMessage)) { $_.ParameterName + " explanation`n`r`n`r"} else {$_.HelpMessage + "`n`r`n`r"}
$OutParams += $CBH_PARAM -replace '%%PARAM%%',$_.ParameterName -replace '%%PARAMHELP%%',$ParamHelpMessage
}
}
else {
}
$OutCBH.'CBH' = $CBHTemplate -replace '%%PARAMETER%%',$OutParams
New-Object PSObject -Property $OutCBH
}
}
Write-Verbose "$($FunctionName): End."
}
}
function New-MBDynamicParameter {
<#
.SYNOPSIS
Helper function to simplify creating dynamic parameters
.DESCRIPTION
Helper function to simplify creating dynamic parameters.
Example use cases:
Include parameters only if your environment dictates it
Include parameters depending on the value of a user-specified parameter
Provide tab completion and intellisense for parameters, depending on the environment
Please keep in mind that all dynamic parameters you create, will not have corresponding variables created.
Use New-DynamicParameter with 'CreateVariables' switch in your main code block,
('Process' for advanced functions) to create those variables.
Alternatively, manually reference $PSBoundParameters for the dynamic parameter value.
This function has two operating modes:
1. All dynamic parameters created in one pass using pipeline input to the function. This mode allows to create dynamic parameters en masse,
with one function call. There is no need to create and maintain custom RuntimeDefinedParameterDictionary.
2. Dynamic parameters are created by separate function calls and added to the RuntimeDefinedParameterDictionary you created beforehand.
Then you output this RuntimeDefinedParameterDictionary to the pipeline. This allows more fine-grained control of the dynamic parameters,
with custom conditions and so on.
.NOTES
Credits to jrich523 and ramblingcookiemonster for their initial code and inspiration:
https://github.com/RamblingCookieMonster/PowerShell/blob/master/New-DynamicParam.ps1
http://ramblingcookiemonster.wordpress.com/2014/11/27/quick-hits-credentials-and-dynamic-parameters/
http://jrich523.wordpress.com/2013/05/30/powershell-simple-way-to-add-dynamic-parameters-to-advanced-function/
Credit to BM for alias and type parameters and their handling
.PARAMETER Name
Name of the dynamic parameter
.PARAMETER Type
Type for the dynamic parameter. Default is string
.PARAMETER Alias
If specified, one or more aliases to assign to the dynamic parameter
.PARAMETER Mandatory
If specified, set the Mandatory attribute for this dynamic parameter
.PARAMETER Position
If specified, set the Position attribute for this dynamic parameter
.PARAMETER HelpMessage
If specified, set the HelpMessage for this dynamic parameter
.PARAMETER DontShow
If specified, set the DontShow for this dynamic parameter.
This is the new PowerShell 4.0 attribute that hides parameter from tab-completion.
http://www.powershellmagazine.com/2013/07/29/pstip-hiding-parameters-from-tab-completion/
.PARAMETER ValueFromPipeline
If specified, set the ValueFromPipeline attribute for this dynamic parameter
.PARAMETER ValueFromPipelineByPropertyName
If specified, set the ValueFromPipelineByPropertyName attribute for this dynamic parameter
.PARAMETER ValueFromRemainingArguments
If specified, set the ValueFromRemainingArguments attribute for this dynamic parameter
.PARAMETER ParameterSetName
If specified, set the ParameterSet attribute for this dynamic parameter. By default parameter is added to all parameters sets.
.PARAMETER AllowNull
If specified, set the AllowNull attribute of this dynamic parameter
.PARAMETER AllowEmptyString
If specified, set the AllowEmptyString attribute of this dynamic parameter
.PARAMETER AllowEmptyCollection
If specified, set the AllowEmptyCollection attribute of this dynamic parameter
.PARAMETER ValidateNotNull
If specified, set the ValidateNotNull attribute of this dynamic parameter
.PARAMETER ValidateNotNullOrEmpty
If specified, set the ValidateNotNullOrEmpty attribute of this dynamic parameter
.PARAMETER ValidateCount
If specified, set the ValidateCount attribute of this dynamic parameter
.PARAMETER ValidateRange
If specified, set the ValidateRange attribute of this dynamic parameter
.PARAMETER ValidateLength
If specified, set the ValidateLength attribute of this dynamic parameter
.PARAMETER ValidatePattern
If specified, set the ValidatePattern attribute of this dynamic parameter
.PARAMETER ValidateScript
If specified, set the ValidateScript attribute of this dynamic parameter
.PARAMETER ValidateSet
If specified, set the ValidateSet attribute of this dynamic parameter
.PARAMETER Dictionary
If specified, add resulting RuntimeDefinedParameter to an existing RuntimeDefinedParameterDictionary.
Appropriate for custom dynamic parameters creation.
If not specified, create and return a RuntimeDefinedParameterDictionary
Aappropriate for a simple dynamic parameter creation.
.PARAMETER CreateVariables
Dynamic parameters don't have corresponding variables created, you need to call New-DynamicParameter with CreateVariables switch to fix that.
.EXAMPLE
Create one dynamic parameter.
This example illustrates the use of New-DynamicParameter to create a single dynamic parameter.
The Drive's parameter ValidateSet is populated with all available volumes on the computer for handy tab completion / intellisense.
Usage: Get-FreeSpace -Drive <tab>
function Get-FreeSpace
{
[CmdletBinding()]
Param()
DynamicParam
{
# Get drive names for ValidateSet attribute
$DriveList = ([System.IO.DriveInfo]::GetDrives()).Name
# Create new dynamic parameter
New-DynamicParameter -Name Drive -ValidateSet $DriveList -Type ([array]) -Position 0 -Mandatory
}
Process
{
# Dynamic parameters don't have corresponding variables created,
# you need to call New-DynamicParameter with CreateVariables switch to fix that.
New-DynamicParameter -CreateVariables -BoundParameters $PSBoundParameters
$DriveInfo = [System.IO.DriveInfo]::GetDrives() | Where-Object {$Drive -contains $_.Name}
$DriveInfo |
ForEach-Object {
if(!$_.TotalFreeSpace)
{
$FreePct = 0
}
else
{
$FreePct = [System.Math]::Round(($_.TotalSize / $_.TotalFreeSpace), 2)
}
New-Object -TypeName psobject -Property @{
Drive = $_.Name
DriveType = $_.DriveType
'Free(%)' = $FreePct
}
}
}
}
.EXAMPLE
Create several dynamic parameters not using custom RuntimeDefinedParameterDictionary (requires piping).
In this example two dynamic parameters are created. Each parameter belongs to the different parameter set, so they are mutually exclusive.
The Drive's parameter ValidateSet is populated with all available volumes on the computer.
The DriveType's parameter ValidateSet is populated with all available drive types.
Usage: Get-FreeSpace -Drive <tab>
or
Usage: Get-FreeSpace -DriveType <tab>
Parameters are defined in the array of hashtables, which is then piped through the New-Object to create PSObject and pass it to the New-DynamicParameter function.
Because of piping, New-DynamicParameter function is able to create all parameters at once, thus eliminating need for you to create and pass external RuntimeDefinedParameterDictionary to it.
function Get-FreeSpace
{
[CmdletBinding()]
Param()
DynamicParam
{
# Array of hashtables that hold values for dynamic parameters
$DynamicParameters = @(
@{
Name = 'Drive'
Type = [array]
Position = 0
Mandatory = $true
ValidateSet = ([System.IO.DriveInfo]::GetDrives()).Name
ParameterSetName = 'Drive'
},
@{
Name = 'DriveType'
Type = [array]
Position = 0
Mandatory = $true
ValidateSet = [System.Enum]::GetNames('System.IO.DriveType')
ParameterSetName = 'DriveType'
}
)
# Convert hashtables to PSObjects and pipe them to the New-DynamicParameter,
# to create all dynamic paramters in one function call.
$DynamicParameters | ForEach-Object {New-Object PSObject -Property $_} | New-DynamicParameter
}
Process
{
# Dynamic parameters don't have corresponding variables created,
# you need to call New-DynamicParameter with CreateVariables switch to fix that.
New-DynamicParameter -CreateVariables -BoundParameters $PSBoundParameters
if($Drive)
{
$Filter = {$Drive -contains $_.Name}
}
elseif($DriveType)
{
$Filter = {$DriveType -contains $_.DriveType}
}
$DriveInfo = [System.IO.DriveInfo]::GetDrives() | Where-Object $Filter
$DriveInfo |
ForEach-Object {
if(!$_.TotalFreeSpace)
{
$FreePct = 0
}
else
{
$FreePct = [System.Math]::Round(($_.TotalSize / $_.TotalFreeSpace), 2)
}
New-Object -TypeName psobject -Property @{
Drive = $_.Name
DriveType = $_.DriveType
'Free(%)' = $FreePct
}
}
}
}
.EXAMPLE
Create several dynamic parameters, with multiple Parameter Sets, not using custom RuntimeDefinedParameterDictionary (requires piping).
In this example three dynamic parameters are created. Two of the parameters are belong to the different parameter set, so they are mutually exclusive.
One of the parameters belongs to both parameter sets.
The Drive's parameter ValidateSet is populated with all available volumes on the computer.
The DriveType's parameter ValidateSet is populated with all available drive types.
The DriveType's parameter ValidateSet is populated with all available drive types.
The Precision's parameter controls number of digits after decimal separator for Free Space percentage.
Usage: Get-FreeSpace -Drive <tab> -Precision 2
or
Usage: Get-FreeSpace -DriveType <tab> -Precision 2
Parameters are defined in the array of hashtables, which is then piped through the New-Object to create PSObject and pass it to the New-DynamicParameter function.
If parameter with the same name already exist in the RuntimeDefinedParameterDictionary, a new Parameter Set is added to it.
Because of piping, New-DynamicParameter function is able to create all parameters at once, thus eliminating need for you to create and pass external RuntimeDefinedParameterDictionary to it.
function Get-FreeSpace
{
[CmdletBinding()]
Param()
DynamicParam
{
# Array of hashtables that hold values for dynamic parameters
$DynamicParameters = @(
@{
Name = 'Drive'
Type = [array]
Position = 0
Mandatory = $true
ValidateSet = ([System.IO.DriveInfo]::GetDrives()).Name
ParameterSetName = 'Drive'
},
@{
Name = 'DriveType'
Type = [array]
Position = 0
Mandatory = $true
ValidateSet = [System.Enum]::GetNames('System.IO.DriveType')
ParameterSetName = 'DriveType'
},
@{
Name = 'Precision'
Type = [int]
# This will add a Drive parameter set to the parameter
Position = 1
ParameterSetName = 'Drive'
},
@{
Name = 'Precision'
# Because the parameter already exits in the RuntimeDefinedParameterDictionary,
# this will add a DriveType parameter set to the parameter.
Position = 1
ParameterSetName = 'DriveType'
}
)
# Convert hashtables to PSObjects and pipe them to the New-DynamicParameter,
# to create all dynamic paramters in one function call.
$DynamicParameters | ForEach-Object {New-Object PSObject -Property $_} | New-DynamicParameter
}
Process
{
# Dynamic parameters don't have corresponding variables created,
# you need to call New-DynamicParameter with CreateVariables switch to fix that.
New-DynamicParameter -CreateVariables -BoundParameters $PSBoundParameters
if($Drive)
{
$Filter = {$Drive -contains $_.Name}
}
elseif($DriveType)
{
$Filter = {$DriveType -contains $_.DriveType}
}
if(!$Precision)
{
$Precision = 2
}
$DriveInfo = [System.IO.DriveInfo]::GetDrives() | Where-Object $Filter
$DriveInfo |
ForEach-Object {
if(!$_.TotalFreeSpace)
{
$FreePct = 0
}
else
{
$FreePct = [System.Math]::Round(($_.TotalSize / $_.TotalFreeSpace), $Precision)
}
New-Object -TypeName psobject -Property @{
Drive = $_.Name
DriveType = $_.DriveType
'Free(%)' = $FreePct
}
}
}
}
.Example
Create dynamic parameters using custom dictionary.
In case you need more control, use custom dictionary to precisely choose what dynamic parameters to create and when.
The example below will create DriveType dynamic parameter only if today is not a Friday:
function Get-FreeSpace
{
[CmdletBinding()]