allcommands.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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
### DO NOT EDIT THIS FILE DIRECTLY ###

#.ExternalHelp HelpOut-Help.xml
function Get-MAML
{
    <#
    .Synopsis
        Gets MAML help
    .Description
        Gets help for a given command, as MAML (Microsoft Assistance Markup Language) xml.
    .Example
        Get-MAML -Name Get-MAML
    .Example
        Get-Command Get-MAML | Get-MAML
    .Example
        Get-MAML -Name Get-MAML -Compact
    .Example
        Get-MAML -Name Get-MAML -XML
    .Link
        Get-Help
    .Link
        Save-MAML
    .INPUTS
        [Management.Automation.CommandInfo]
        Accepts a command
    .Outputs
        [String]
        The MAML, as a String. This is the default.
    .Outputs
        [Xml]
        The MAML, as an XmlDocument (when -XML is passed in)
    #>

    [CmdletBinding(DefaultParameterSetName='CommandInfo')]
    [OutputType([string],[xml])]
    [Alias('ConvertTo-MAML')]
    param( 
    # The name of or more commands.
    [Parameter(ParameterSetName='ByName',Position=0,ValueFromPipelineByPropertyName=$true)]
    [string[]]
    $Name,

    # The name of one or more modules.
    [Parameter(ParameterSetName='ByModule',ValueFromPipelineByPropertyName=$true)]
    [string[]]
    $Module,

    # The CommandInfo object (returned from Get-Command).
    [Parameter(Mandatory=$true,ParameterSetName='FromCommandInfo', ValueFromPipeline=$true)]
    [Management.Automation.CommandInfo[]]
    $CommandInfo,

    # If set, the generated MAML will be compact (no extra whitespace or indentation). If not set, the MAML will be indented.
    [switch]
    $Compact,
    
    # If set, will return the MAML as an XmlDocument. The default is to return the MAML as a string.
    [switch]
    $XML,
    
    # If set, the generate MAML will not contain a version number.
    # This slightly reduces the size of the MAML file, and reduces the rate of changes in the MAML file.
    [Alias('Unversioned')]
    [switch]
    $NoVersion)
    
    begin {
        # First, we need to create a list of all commands we encounter (so we can process them at the end)
        $allCommands = [Collections.ArrayList]::new()
        # Then, we want to get the type accelerators (so we don't have to keep getting them each time we're interested)
        $typeAccelerators = [PSOBject].Assembly.GetType('System.Management.Automation.TypeAccelerators')::Get

        # Next up, we're going to declare a bunch of ScriptBlocks, which we'll call to construct the XML in pieces.
        # This way we can create a nested structure (in this case, XML), by calling the pieces we want and letting them return the XML in chunks


        #region Get TypeName
        $GetTypeName = {param([Type]$t)
            # We'll want to check to see if there are any accelerators.
            if (-not $typeAccelerators -and $typeAccelerators.GetEnumerator) {  # If there weren't
                return $t.Fullname # return the fullname.
            }
             
            foreach ($_ in $typeAccelerators.GetEnumerator()) { # Loop through the accelerators.
                if ($_.Value -eq $t) { # If it's an accelrator for the target type
                    return $_.Key.Substring(0,1).ToUpper() + $_.Key.Substring(1) # return the key (and fix it's casing)
                }
            }
            return $t.Fullname # If we didn't find it in the accelerators list, return the fullname.
        }
        #endregion Get TypeName

        #region Write Type

        # Both Inputs and Outputs have the same internal tag structure for a value, so one script block handles both cases.
        $WriteType = {param($t) 
            $typename = $t.type[0].name
            $descriptionLines = $null
            
            
            if ($in.description) { # If we have a description,
                $descriptionLines = $in.Description[0].text -split "`n|`r`n" -ne '' # we we're good.
            } else { # If we didn't, it's probably because comment based help mangles things a bit (it puts everything in a long typename).
                # Let's fix this by assigning the inType from the first line, and setting the rest as description lines
                $typename, $descriptionLines = $t.type[0].Name -split "`n|`r`n" -ne ''
            }
            $typename = [Security.SecurityElement]::Escape("$typename".Trim())
            

            "<dev:type><maml:name>$typename</maml:name><maml:uri/><maml:description /></dev:type>" # Write the type information
            if ($descriptionLines) { # If we had a description
                '<maml:description>' 
                foreach ($line in $descriptionLines) { # Write each line in it's own para tag so that it renders right.
                    $esc = [Security.SecurityElement]::Escape($line)
                    "<maml:para>$esc</maml:para>"
                }
                '</maml:description>'
            }
        }
        #endregion Write Type

        #region Write Command Details
        $writeCommandDetails = {
            # The command.details tag has 5 parts we want to provide
            # * Name,
            # * Noun
            # * Verb
            # * Synopsis
            # * Version
            $Version = "<dev:version>$(if ($cmdInfo.Version) { $cmdInfo.Version.ToString() })</dev:version>"
           
            "<command:details>
                <command:name>$([Security.SecurityElement]::Escape($cmdInfo.Name))</command:name>
                <command:noun>$noun</command:noun>
                <command:verb>$verb</command:verb>
                <maml:description>
                    <maml:para>$([Security.SecurityElement]::Escape($commandHelp.Synopsis))</maml:para>
                </maml:description>
                $(if (-not $NoVersion) { $Version})
            </command:details>
            <maml:description>
                $(
                foreach ($line in @($commandHelp.Description)[0].text -split "`n|`r`n") {
                    if (-not $line) { continue }
                    "<maml:para>$([Security.SecurityElement]::Escape($Line))</maml:para>"
                    }
                )
            </maml:description>
            "

        }
        #endregion Write Command Details
        
        #region Write Parameter
        $WriteParameter = {
            # Prepare the command.parameter attributes:
            $position  = if ($param.Position -ge 0) { $param.Position } else {"named" } #* Position
            $fromPipeline = #*FromPipeline
                if ($param.ValueFromPipeline) { "True (ByValue)" }
                elseif ($param.ValueFromPipelineByPropertyName) { "True (ByPropertyName)" }
                else { "False" } 
            $isRequired = if ($param.IsMandatory) { "true" } else { "false" } #*Required
            
            
            # Pick out the help for a given parameter
            $paramHelp = foreach ($_ in $commandHelp.parameters.parameter) {
                    if ( $_.Name -eq $param.Name ){
                        $_
                        break
                    }
                }
            $paramTypeName = & $GetTypeName $param.ParameterType # and get the type name of the parameter type.
                                
            "<command:parameter required='$isRequired' position='$position' pipelineInput='$fromPipeline' aliases='' variableLength='true' globbing='false'>" #* Echo the start tag
            "<maml:name>$($param.Name)</maml:name>" #* The maml.name tag
            '<maml:description>' #*The description tag
            foreach ($d in $paramHelp.Description) { 
                "<maml:para>$([Security.SecurityElement]::Escape($d.Text))</maml:para>"
            }
            '</maml:description>' 
            #*The parameterValue tag (which oddly enough, describes the parameter type)
            "<command:parameterValue required='$isRequired' variableLength='true'>$paramTypeName</command:parameterValue>" 
            #*The type tag (which is also it's type)
            "<dev:type><maml:name>$paramTypeName</maml:name><maml:uri /></dev:type>"
            #*and an empty default value.
            '<dev:defaultValue></dev:defaultValue>'
            #* Then close the parameter tag.
            '</command:parameter>'
        }
        #endregion Write Parameter

        #region Write Parameters
        $WriteCommandParameters = {
            '<command:parameters>' # *Open the parameters tag;
            foreach ($param in ($cmdMd.Parameters.Values | Sort-Object Name)) { #*Loop through the command's parameters alphabetically
                & $WriteParameter #*Write each parameter.
            }
            '</command:parameters>' #*Close the parameters tag
        } 
        #endregion Write Parameters


        #region Write Examples
        $WriteExamples = {
            # If there were no examples, return.
            if (-not $commandHelp.Examples.example) { return }

            
            "<command:examples>" 
            foreach ($ex in $commandHelp.Examples.Example) { # For each example:
                '<command:example>' #*Start an example tag
                '<maml:title>'
                $ex.Title  #*Put it's title in a maml:title tag
                '</maml:title>'
                '<maml:introduction>'#* Put it's introduction in a maml:introduction tag
                foreach ($i in $ex.Introduction) {
                    '<maml:para>'
                    [Security.SecurityElement]::Escape($i.Text)
                    '</maml:para>'
                }
                '</maml:introduction>'
                '<dev:code>' #* Put it's code in a dev:code tag
                [Security.SecurityElement]::Escape($ex.Code)
                '</dev:code>'
                '<dev:remarks>' #* Put it's remarks in a dev:remarks tag
                foreach ($i in $ex.Remarks) {
                    if (-not $i -or -not $i.Text.Trim()) { continue }                        
                    '<maml:para>'
                    [Security.SecurityElement]::Escape($i.Text)
                    '</maml:para>'
                }
                '</dev:remarks>'
                '</command:example>'
            }
            '</command:examples>'
        }
        #endregion Write Examples

 

        #region Write Inputs
        $WriteInputs = {
            if (-not $commandHelp.inputTypes) { return } # If there were no input types, return.


            '<command:inputTypes>' #*Open the inputTypes Tag.
            foreach ($in in $commandHelp.inputTypes[0].inputType) { #*Walk thru each type in help.
                '<command:inputType>'  
                    & $WriteType $in #*Write the type information (in an inputType tag).
                '</command:inputType>'
            }
            '</command:inputTypes>' #*Close the Input Types Tag.
        }
        #endregion Write Inputs

        #region Write Outputs
        $WriteOutputs = {
            if (-not $commandHelp.returnValues) { return } # If there were no return values, return.
            
            '<command:returnValues>' # *Open the returnValues tag
            foreach ($rt in $commandHelp.returnValues[0].returnValue) { # *Walk thru each return value
                '<command:returnValue>' 
                    & $WriteType $rt # *write the type information (in an returnValue tag)
                '</command:returnValue>'
            }
            '</command:returnValues>' #*Close the returnValues tag
        }
        #endregion Write Outputs

        #region Write Notes
        $WriteNotes = {
            if (-not $commandHelp.alertSet) { return } # If there were no notes, return.
            "<maml:alertSet><maml:title></maml:title>" #*Open the alertSet tag and emit an empty title
            foreach ($note in $commandHelp.alertSet[0].alert) { #*Walk thru each note
                "<maml:alert><maml:para>"                    
                    $([Security.SecurityElement]::Escape($note.Text)) #*Put each note in a maml:alert element
                "</maml:para></maml:alert>"
            } 
            "</maml:alertSet>" #*Close the alertSet tag
        }
        #endregion Write Notes

        #region Write Syntax
        $WriteSyntax = {
            if (-not $cmdInfo.ParameterSets) { return } # If this command didn't have parameters, return
            
            "<command:syntax>" #*Open the syntax tag
            foreach ($syn in $cmdInfo.ParameterSets) {#*Walk thru each parameter set
                "<command:syntaxItem><maml:name>$($cmdInfo.Name)</maml:name>"  #*Create a syntaxItem tag, with the name of the command.
                foreach ($param in $syn.Parameters) { 
                    #* Skip parameters that are not directly declared (e.g. -ErrorAction)
                    if (-not $cmdMd.Parameters.ContainsKey($param.Name))  { continue } 
                    & $WriteParameter #* Write help for each parameter
                }
                "</command:syntaxItem>" #*Close the syntax item tag
            }
            "</command:syntax>"#*Close the syntax tag
            
        }
        #endregion Write Syntax

        #region Write Links
        $WriteLinks = {
            # If the command didn't have any links, return.
            if (-not $commandHelp.relatedLinks.navigationLink) { return }
            
            '<maml:relatedLinks>' #* Open a related Links tag
            foreach ($l in $commandHelp.relatedLinks.navigationLink) { #*Walk thru each link
                $linkText, $LinkUrl = "$($l.linkText)".Trim(), "$($l.Uri)".Trim() # and write it's tag.
                '<maml:navigationLink>'
                    "<maml:linkText>$linkText</maml:linkText>"
                    "<maml:uri>$LinkUrl</maml:uri>"
                '</maml:navigationLink>'
            }
            '</maml:relatedLinks>' #* Close the related Links tag
        }    
        #endregion Write Links


        #- - - Now that we've declared all of these little ScriptBlock parts, we'll put them in a list in the order they'll run.
        $WriteMaml = $writeCommandDetails, $writeSyntax,$WriteCommandParameters,$WriteInputs,$writeOutputs, $writeNotes, $WriteExamples, $writeLinks
        #- - -
    }
    
    process {
        
        if ($PSCmdlet.ParameterSetName -eq 'ByName') { # If we're getting comamnds by name,
            $CommandInfo = @(foreach ($n in $name) { 
                $ExecutionContext.InvokeCommand.GetCommands($N,'Function,Cmdlet', $true) # find each command (treating Name like a wildcard).
            })
        }


        if ($PSCmdlet.ParameterSetName -eq 'ByModule') { # If we're getting commands by module
            $CommandInfo = @(foreach ($m in $module) {  # find each module
                (Get-Module -Name $m).ExportedCommands.Values # and get it's exports.
            })
        }


        $filteredCmds = @(foreach ($ci in $CommandInfo) { # Filter the list of commands
            if ($ci -is [Management.Automation.AliasInfo] -or # (throw out aliases and applications).
                $ci -is [Management.Automation.ApplicationInfo]) { continue }
            $ci 
        })
         
        if ($filteredCmds) { 
            $null = $allCommands.AddRange($filteredCmds)
        }
    }
    
    end {
        $c, $t, $id, $maml = # Create some variables for our progress bar,
        0, $allCommands.Count, [Random]::new().Next(), [Text.StringBuilder]::new('<helpItems schema="maml">') # and initialize our MAML.
        
        foreach ($cmdInfo in $allCommands) { # Walk thru each command.
            $commandHelp = $null
            $c++
            $p = $c * 100 / $t
            Write-Progress 'Converting to MAML' "$cmdInfo [$c of $t]" -PercentComplete $p -Id $id # Write a progress message
            $commandHelp = $cmdInfo | Get-Help # get it's help
            $cmdMd = [Management.Automation.CommandMetaData]$cmdInfo # get it's command metadata
            if (-not $commandHelp -or $commandHelp -is [string]) { # (error if we couldn't Get-Help)
                Write-Error "$cmdInfo Must have a help topic to convert to MAML"
                return
            }                
            $verb, $noun  = $cmdInfo.Name -split "-" # and split out the noun and verb.
            


            # Now we're ready to run all of those script blocks we declared in begin.
            # All we need to do is append the command node, run each of the script blocks in $WriteMaml, and close the node.
            $mamlCommand = 
                "<command:command
                    xmlns:maml='http://schemas.microsoft.com/maml/2004/10'
                    xmlns:command='http://schemas.microsoft.com/maml/dev/command/2004/10'
                    xmlns:dev='http://schemas.microsoft.com/maml/dev/2004/10'>
                    $(foreach ($_ in $WriteMaml) { & $_ })
                </command:command>"

            $null = $maml.AppendLine($mamlCommand)
        }

        Write-Progress "Exporting Maml" " " -Completed -Id $id # Then we indicate we're done,
        $null = $maml.Append("</helpItems>") # close the opening tag.
        $mamlAsXml = [xml]"$maml" # and convert the whole thing to XML.
        if (-not $mamlAsXml) { return }  # If we couldn't, return.
        
        
        if ($XML) { return $mamlAsXml } # If we wanted the XML, return it.

        
        $strWrite = [IO.StringWriter]::new() # Now for a little XML magic:


        # If we create a [IO.StringWriter], we can save it as pretty or compacted XML.
        $mamlAsXml.PreserveWhitespace = $Compact # Oddly enough, if we're compacting we're setting preserveWhiteSpace to true, which in turn strips all of the whitespace except that inside of your nodes.
        $mamlAsXml.Save($strWrite) # Anyways, we can save this to the string writer, and it will either make our XML perfectly balanced and indented or compact and free of most whitespace.
        # Unfortunately, it will not get it's encoding declaration "right". This is because $strWrite is Unicode, and in most cases we'll want our XML to be UTF8.
        # The next step of the pipeline needs to convert it as it is saved, which is as easy as | Out-File -Encoding UTF8.
        "$strWrite".Replace('<?xml version="1.0" encoding="utf-16"?>','<?xml version="1.0" encoding="utf-8"?>') 
        $strWrite.Close()
        $strWrite.Dispose()
    }
} 
#.ExternalHelp HelpOut-Help.xml
function Get-MarkdownHelp {
    <#
    .SYNOPSIS
        Gets Markdown Help
    .DESCRIPTION
        Gets Help for a given command, in Markdown
    .EXAMPLE
        Get-MarkdownHelp Get-Help
    .LINK
        Save-MarkdownHelp
    .LINK
        Get-Help
    .OUTPUTS
        [string]

        The documentation for a single command, in Markdown.
    #>

    [Reflection.AssemblyMetadata("HelpOut.TellStory", $true)]
    [Reflection.AssemblyMetadata("HelpOut.Story.Process", "For each Command")]
    [OutputType('PowerShell.Markdown.Help')]
    param(
    # The name of the specified command or concept.
    [Parameter(Position=0, ValueFromPipelineByPropertyName)]
    [ValidateNotNullOrEmpty()]
    [string]
    $Name,

    # If set, will generate a markdown wiki. Links will be relative to the current path, and will not include the .md extensions
    [switch]
    $Wiki,

    # If set, will interlink documentation as if it were for GitHub pages, beneath a given directory
    [Alias('GitHubPageRoot')]
    [string]
    $GitHubDocRoot,

    # If provided, will rename the help topic before getting markdown.
    [Parameter(ValueFromPipelineByPropertyName)]
    [string]
    $Rename,

    # The order of the sections.
    # If not provided, this will be the order they are defined in the formatter.
    [Parameter(ValueFromPipelineByPropertyName)]
    [string[]]
    $SectionOrder,

    # If set, will not enumerate valid values and enums of parameters.
    [Parameter(ValueFromPipelineByPropertyName)]
    [switch]
    $NoValidValueEnumeration,

    # If set, will not attach a YAML header to the generated help.
    [Parameter(ValueFromPipelineByPropertyName)]
    [Alias('IncludeFrontMatter', 'IncludeHeader')]
    [switch]
    $IncludeYamlHeader,

    # The type of information to include in the YAML Header
    [ValidateSet('Command','Help','Metadata')]
    [Alias('YamlHeaderInfoType')]
    [string[]]
    $YamlHeaderInformationType
    )

    process
    {
        # We start off by copying the bound parameters
        $myParams= @{} + $PSBoundParameters
        # and then we call Get-Help.
        $getHelp = @{name=$Name}
        $gotHelp = Get-Help @getHelp
        
        
        # If we could not Get-Help,
        if (-not $gotHelp) {
            Write-Error "Could not get help for $name"
            return # we error out.
        }

        # We need to decorate the output of Get-Help so it renders as markdown,
        # so we pipe thru all results from Get-Help.

        $gotHelp |
            & { process {
                    # Get-Help can return either a help topic or command help.
                    $in = $_
                    # Help topics will be returned as a string
                    if ($in -is [string]) {
                        $in # (which we will output as-is for now).
                    } else {


                        
                        $helpObj = $_
                        # Command Help will be returned as an object
                        # We decorate that object with the typename `PowerShell.Markdown.Help`.
                        $helpObj.pstypenames.clear()
                        $helpObj.pstypenames.add('PowerShell.Markdown.Help')

                        # Then we attach parameters passed to this command to the help object.
                        # * `-Rename` will become `[string] .Rename`
                        if ($Rename) {
                            $helpObj | Add-Member NoteProperty Rename $Rename -Force
                        }

                        # * `-SectionOrder` will become `[string[]] .SectionOrder`
                        if ($SectionOrder) {
                            $helpObj | Add-Member NoteProperty SectionOrder $SectionOrder -Force
                        }
                        # * `-Wiki` will become `[bool] .WikiLink`
                        $helpObj | Add-Member NoteProperty WikiLink ($Wiki -as [bool]) -Force
                        # * `-GitHubDocRoot` will become `.DocLink`
                        if ($myParams.ContainsKey("GitHubDocRoot")) {
                            $helpObj | Add-Member NoteProperty DocLink $GitHubDocRoot -Force
                        }
                        # * `-NoValidValueEnumeration`
                        $helpObj | Add-Member NoteProperty NoValidValueEnumeration $NoValidValueEnumeration -Force
                        # * `-IncludeYamlHeader`
                        $helpObj | Add-Member NoteProperty IncludeYamlHeader $IncludeYamlHeader -Force
                        # * `-NoValidValueEnumeration`
                        $helpObj | Add-Member NoteProperty YamlHeaderInformationType $YamlHeaderInformationType -Force


                        # After we've attached all of the properties, we simply output the object.
                        # PowerShell.Markdown.Help formatter will display it exactly as we'd like it.
                        $helpObj
                    }
                }
            }
    }
}
 #requires -version 3.0
function Get-ScriptReference
{
    <#
    .Synopsis
        Gets a script's references
    .Description
        Gets the external references of a given PowerShell command. These are the commands the script calls, and the types the script uses.
    .Example
        Get-Command Get-ScriptReference | Get-ScriptReference
    #>

    [CmdletBinding(DefaultParameterSetName='FilePath')]
    param(
    # The path to a file
    [Parameter(Mandatory=$true,Position=0,ParameterSetName='FilePath',ValueFromPipelineByPropertyName=$true)]
    [Alias('Fullname')]
    [string[]]
    $FilePath,

    # One or more PowerShell ScriptBlocks
    [Parameter(Mandatory=$true,Position=0,ParameterSetName='ScriptBlock',ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
    [Alias('Definition')]
    [ScriptBlock[]]
    $ScriptBlock,

    # If set, will recursively find references.
    [switch]
    $Recurse
    )


    begin {
        # Let's declare some collections we'll need:
        $allFiles = [Collections.ArrayList]::new() # * A list of all files (if any are piped in)
        $LookedUpCommands = @{} # * The commands we've already looked up (to save time)
    }
    process {
        
        #region Process Piped in Files
        if ($PSCmdlet.ParameterSetName -eq 'FilePath') { # If we're piping in files,
            $allFiles.AddRange($FilePath) # add them to the list and process them in the end,
            return # and stop processing for good measure.
        }
        #endregion Process Piped in Files
                
        #region Get the Script References
        
        # To start off with, take all of the scripts passed in and put them in a queue.
        $scriptBlockQueue = [Collections.Generic.Queue[ScriptBlock]]::new($ScriptBlock)
        $resolvedCmds = @{} # Then create a hashtable to store the resolved references
        $alreadyChecked = [Collections.Generic.List[ScriptBlock]]::new() # and a list of all of the ScriptBlock's we've already taken a look at.

        # Now it's time for some syntax trickery that should probably be explained.
        
        
        # We're going to want to be able to recursively find references too.
        # By putting this in a queue, we've already done part of the work,
        # because we can just enqueue the nested commands.
        # However, we also want to know _which nested command had which references_
        # This means we have to collect all of the references as we go,
        # and output them in a different way if we're running recursively.


        # Got all that?
        
        
        # First, we need a tracking variable
        $CurrentCommand = '.' # for the current command.

        # Now the syntax trickery: We put the do loop inside of a lambda running in our scope (. {}).
        # This gives us all of our variables, but lets the results stream to the pipeline.
        # This is actually pretty important, since this way our tracking variable is accurate when we're outputting the results.
        
        # Now that we understand how it works, let's get to:
        
        #region Process the Queue of Script Blocks
        
        . { 
            $alreadyChecked = [Collections.ArrayList]::new()
            do { 
                $scriptBlock = $scriptBlockQueue.Dequeue()                
                if ($alreadyChecked -contains $scriptBlock) { continue } 
                $null=  $alreadyChecked.Add($ScriptBlock)
                $foundRefs = $Scriptblock.Ast.FindAll({
                    param($ast) 
                    $ast -is [Management.Automation.Language.CommandAst] -or 
                    $ast -is [Management.Automation.Language.TypeConstraintAst] -or 
                    $ast -is [Management.Automation.Language.TypeExpressionAst]
                }, $true)


                $cmdRefs = [Collections.ArrayList]::new()
                $cmdStatements = [Collections.ArrayList]::new()
                $typeRefs = [Collections.ArrayList]::new()

                foreach ($ref in $foundRefs) {
                    if ($ref -is [Management.Automation.Language.CommandAst]) {                    
                        $null = $cmdStatements.Add($ref)
                        if (-not $ref.CommandElements) { continue } 
                        $theCmd = $ref.CommandElements[0]
                        if ($theCmd.Value) {
                            
                            if (-not $LookedUpCommands[$theCmd.Value]) {
                                $LookedUpCommands[$thecmd.Value] = $ExecutionContext.InvokeCommand.GetCommand($theCmd.Value, 'Cmdlet, Function, Alias')
                            }
                            if ($cmdRefs -notcontains $LookedUpCommands[$theCmd.Value]) {
                                $null = $cmdRefs.Add($LookedUpCommands[$thecmd.Value])                            
                            }
                        } else {
                            # referencing a lambda, leave it alone for now
                        }
                    } elseif ($ref.TypeName) {
                        $refType = $ref.TypeName.Fullname -as [type]
                        if ($typeRefs -notcontains $refType) {
                            $null = $typeRefs.Add($refType)
                        }                        
                    }
                }


                [PSCustomObject][Ordered]@{
                    Commands = $cmdRefs.ToArray()
                    Statements = $cmdStatements.ToArray()
                    Types = $typeRefs.ToArray()
                }

                

            if ($Recurse) {
                $uniqueCmdRefs | 
                    & { process {
                        if ($resolvedCmds.ContainsKey($_.Name)) { return }
                        $nextScriptBlock = $_.ScriptBlock
                        if (-not $nextScriptBlock -and $_.ResolvedCommand.ScriptBlock)  {
                            $nextScriptBlock = $_.ResolvedCommand.ScriptBlock
                        }
                        if ($nextScriptBlock) { 
                            $scriptBlockQueue.Enqueue($nextScriptBlock)
                            $resolvedCmds[$_.Name] = $true
                        }
                    } }                 
            }                
        } while ($ScriptBlockQueue.Count) } | 
        #endregion Process the Queue of Script Blocks
        #region Handle Each Output
            & { 
                begin {
                    $refTable = @{}
                }
                process {
                    if (-not $Recurse) { return $_ } 
                }
            }
        #endregion Handle Each Output
        #endregion Get the Script References
                    
    }

    end {
        $myParams = @{} + $PSBoundParameters
        if (-not $allFiles.Count) { return }
        $c, $t, $id = 0, $allFiles.Count, $(Get-Random)
        foreach ($file in $allFiles) {
            $c++ 
            $resolvedFile=  try { $ExecutionContext.SessionState.Path.GetResolvedPSPathFromPSPath($file)} catch { $null }
            if (-not $resolvedFile) { continue } 
            $resolvedFile = [IO.FileInfo]"$resolvedFile"
            if (-not $resolvedFile.Name) { continue }
            if (-not $resolvedFile.Length) { continue }
            if ('.ps1', '.psm1' -notcontains $resolvedFile.Extension) { continue }   
            $p = $c * 100 / $t
            $text = [IO.File]::ReadAllText($resolvedFile.FullName)
            $scriptBlock= [ScriptBlock]::Create($text)
            Write-Progress "Getting References" " $($resolvedFile.Name) " -PercentComplete $p -Id $id
            if (-not $scriptBlock) { continue }
            
            Get-ScriptReference -ScriptBlock $scriptBlock |
                & { process {
                    $_.psobject.properties.add([Management.Automation.PSNoteProperty]::new('FileName',$resolvedFile.Name))
                    $_.psobject.properties.add([Management.Automation.PSNoteProperty]::new('FilePath',$resolvedFile.Fullname))
                    $_.pstypenames.add('HelpOut.Script.Reference')
                    $_  
                } }                

            Write-Progress "Getting References" " " -Completed -Id $id
        }
    }
} 
#.ExternalHelp HelpOut-Help.xml
function Get-ScriptStory
{
    <#
    .Synopsis
        Gets a Script's story
    .Description
        Gets the Script's "Story"
 
        Script Stories are a simple markdown summary of all single-line comments within a script (aside from those in the param block).
    .Example
        Get-Command Get-ScriptStory | Get-ScriptStory
    .Notes
         
    #>

    [CmdletBinding(DefaultParameterSetName='ScriptBlock')]
    param(
    # A script block
    [Parameter(Mandatory=$true,Position=0,ValueFromPipeline=$true,ParameterSetName='ScriptBlock')]
    [ScriptBlock]
    $ScriptBlock,

    # A block of text
    [Parameter(Mandatory=$true,Position=0,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,ParameterSetName='ScriptText')]
    [Alias('ScriptContents', 'Definition')]
    [string]
    $Text,
    
    # The friendly names of code regions or begin,process, or end blocks.
    [Collections.IDictionary]
    $RegionName = @{
        begin = "Before any input"
        process = "On Each Input"
        end = "After all input"
    },
    
    [int]
    $HeadingSize = 3)

    process {
        function foo($x, $y) {
            # Documentation should be ignored
        }

        # First, we want to convert any text input to -ScriptBlock.
        if ($PSCmdlet.ParameterSetName -eq 'ScriptText') {
            $ScriptBlock = [ScriptBlock]::Create($Text)
        }

        # Next, we tokenize the script and force it into an array.
        $tokens = @([Management.Automation.PSParser]::Tokenize("$ScriptBlock", [ref]$null))
        # We need to keep track of how many levels of regions we're in, so create a $RegionStack.
        $regionStack = [Collections.Stack]::new()
        # We'll also want to make a StringBuilder (because it will be faster).
        $sb= [text.stringbuilder]::new()
        # Last but not least, we'll want to keep track of a block depth, so initialize that to zero.
        $blockDepth = 0 
        #region Walk Thru Tokens
        for ($i =0; $i -lt $tokens.Length; $i++) {
            
            # As we pass GroupStarts and GroupEnds, nudge the block depth.
            if ($tokens[$i].Type -eq 'GroupStart') { $blockDepth++ }
            if ($tokens[$i].Type -eq 'GroupEnd') { $blockDepth-- } 

            #region Handle natural regions
            
            # In addition to any regions specified in documentation,
            # we can treat the begin, process, and end blocks as effective regions.
            if ($tokens[$i].Type -eq 'keyword' -and 
                'begin', 'process', 'end' -contains $tokens[$i].content -and 
                $blockDepth -le 1 ) {
                # When we encounter one of these regions, pop the region stack
                if ($regionStack.Count) { $null = $regionStack.Pop() }
                # and push the current region.
                $null =$regionStack.Push($tokens[$i].Content)


                # Generate the header, which consists of:
                $keywordHeader = 
                    # a newline,
                    [Environment]::NewLine + 
                    # N Markdown headers,
                    ('#' * ([Math]::Min(6, $regionStack.Count + $HeadingSize - 1))) + ' ' +
                    # the friendly name for the region (or just it's content),
                    $(if ($RegionName[$tokens[$i].Content]) {
                        $RegionName[$tokens[$i].Content]
                    } else { 
                        $tokens[$i].Content
                    }) +
                    # and another newline.
                    [Environment]::NewLine

                # Then, append the header.
                $null = $sb.Append($keywordHeader)
                continue
            }
            #endregion Handle natural regions

            #region Skip Parameter Block

            # We don't want all of the documentation.


            # Specifically, we want to avoid any parameter documentation and nested functions.
            # To do this, we need to notice the param and function keyword when it shows up.
            if ($tokens[$i].Type -eq 'keyword' -and 'param', 'function' -contains $tokens[$i].Content) {
                
                
                # Once we've found it, we advance until we find the next GroupStart.
                $j = $i + 1  
                while ($tokens[$j].Type -ne 'GroupStart') { $j++ }

                
                $skipGroupCount = 1
                if ($tokens[$j].Content -eq '(' -and  # If the GroupStart was an open paranthesis
                    $tokens[$i].Content -eq 'function'# and we're dealing with a nested function,
                ) {
                    $skipGroupCount = 2 # we're going to need to this next bit twice.
                }


                foreach ($n in 1..$skipGroupCount) {
                    # Look for the GroupStart.
                    while ($tokens[$j].Type -ne 'GroupStart') { $j++ }                
                    # Then we set a variable to track depth
                    $depth = 0  
                    do {
                        # and walk thru the tokens
                        if ($tokens[$j].Type -eq 'GroupStart') { $depth++ }
                        if ($tokens[$j].Type -eq 'GroupEnd') { $depth-- }
                        $j++
                    } while ($depth -and $tokens[$j]) # until the depth is 0 again.
                }

                
                $i = $j # Finally we set the iterator to current position (thus skipping the param block).
            }
            #endregion Skip Parameter Block

            #region Check for Paragraph Breaks

            # Next we need to check for paragraph breaks.
            
            if ($i -ge 2 -and
                $tokens[$i].Type -eq 'Newline' -and # If the current token is a newline,
                $tokens[$i -1].Type -eq 'Newline')  # and the token before that was also a newline,
            {
                # then it's probably a paragraph break
                if ($i -ge 3 -and $tokens[$i - 2].Type -eq 'GroupEnd') 
                {
                    # (Unless it followed a GroupEnd).
                    continue
                }


                # When we encounter a paragraph break, output two newlines.
                $null = $sb.Append([Environment]::NewLine * 2)
            }
            #endregion Check for Paragraph Breaks

            #region Process Comments

            # At this point, we don't care about anything other than comments.
            # So if it's not a comment, continue past them.
            if ($tokens[$i].Type -ne 'Comment') { continue }
            $Comment = $tokens[$i].Content.Trim([Environment]::NewLine).Trim()  
            if ($Comment.StartsWith('<')) { # If it's a block comment,
                # make sure it's not a special-purpose block comment (like inline help).
                $trimmedComment = $comment.Trim('<#').Trim([Environment]::NewLine).Trim()
                if ('?', '.', '{','-','|' -contains $trimmedComment[0]) { # If it was,
                    continue  # continue on.
                }
                # If it wasn't, trim the block comment and newlines.
                $Comment = $Comment.Trim().Trim("><#").Trim([Environment]::NewLine)
            }
                        
            
            # We'll need to know if it's a region
            # so we'll use some fancy Regex to extract it's name
            # (and if it's an EndRegion or not).

            if ($Comment.Trim() -match '#(?<IsEnd>end){0,1}region(?<RegionName>.{1,})') {
                $thisRegionName = $Matches.RegionName.Trim()
                if ($Matches.IsEnd) {
                    # If it was an EndRegion, pop it off of the Region Stack.
                    $null = $regionStack.Pop()
                } else {
                    # If it wasn't, push it onto the Region Stack.
                    $null = $regionStack.Push($thisRegionName)
                    # Then, output it's name a markdown header,
                    # using the count of RegionStack to determine H1, H2, etc.
                    $regionContent = 
                        [Environment]::NewLine + 
                        ('#' * ([Math]::Min(6, $regionStack.Count + $HeadingSize - 1))) + ' '+ 
                        $(if ($RegionName[$thisRegionName]) {
                            $RegionName[$thisRegionName]
                        } else { 
                            $Matches.RegionName.Trim()
                        }) +
                        [Environment]::NewLine
                    $null = $sb.Append($regionContent)
                }


                # We still don't want the region name to become part of the story,
                # so continue to the next token.
                continue
            }


            # Whatever comment is left is new story content.
            $newStory = $Comment.TrimStart('#').Trim()
                        
            # If there's any content already,
            if ($sb.Length) {
                # before we put it into the string,
                $null = 
                    if ($sb[-1] -eq '.') {
                        # add a double space (after a period),
                        $sb.Append(' ')
                    } else {
                        # or a single space.
                        $sb.Append(' ')   
                    }                
            }
            
            $shouldHaveNewline = 
                $newStory.StartsWith('*') -or 
                $newStory.StartsWith('-') -or 
                ($lastStory -and ($lastStory.StartsWith('*') -or $lastStory.StartsWith('-')))
            if ($shouldHaveNewline) {
                $null = $sb.Append([Environment]::NewLine)
            }
            # Finally, append the new story content.
            $null = $sb.Append($newStory)
            #endregion Process Comments
        }


        #endregion Walk Thru Tokens
    
        
        # After everything is done, output the content of the string builder.
        "$sb"
    }
}

 
 
#.ExternalHelp HelpOut-Help.xml
function Install-MAML
{
    <#
    .Synopsis
        Installs MAML into a module
    .Description
        Installs MAML into a module.
        
        This generates a single script that:
        * Includes all commands
        * Removes their multiline comments
        * Directs the commands to use external help
        
        You should then include this script in your module import.

        Ideally, you should use the allcommands script
    .Example
        Install-MAML -Module HelpOut
    .Link
        Save-MAML
    .Link
        ConvertTo-MAML
    #>

    [OutputType([Nullable], [IO.FileInfo])]
    param(
    # The name of one or more modules.
    [Parameter(Mandatory=$true,Position=0,ParameterSetName='Module',ValueFromPipelineByPropertyName=$true)]
    [string[]]
    $Module,
    
    # If set, will refresh the documentation for the module before generating the commands file.
    [Parameter(ValueFromPipelineByPropertyName=$true)]
    [switch]
    $NoRefresh,

    # If set, will compact the generated MAML. This will be ignored if -Refresh is not passed, since no new MAML will be generated.
    [Parameter(ValueFromPipelineByPropertyName=$true)]
    [switch]
    $Compact,
   
    # The name of the combined script. By default, allcommands.ps1.
    [Parameter(Position=1,ValueFromPipelineByPropertyName=$true)]
    [string]
    $ScriptName = 'allcommands.ps1',

    # The root directories containing functions. If not provided, the function root will be the module root.
    [Parameter(ValueFromPipelineByPropertyName=$true)]
    [string[]]
    $FunctionRoot,

    # If set, the function roots will not be recursively searched.
    [Parameter(ValueFromPipelineByPropertyName=$true)]
    [switch]
    $NoRecurse,

    # The encoding of the combined script. By default, UTF8.
    [Parameter(Position=2,ValueFromPipelineByPropertyName=$true)]
    [ValidateNotNull()]
    [Text.Encoding]
    $Encoding = [Text.Encoding]::UTF8,

    # A list of wildcards to exclude. This list will always contain the ScriptName.
    [Parameter(ValueFromPipelineByPropertyName=$true)]
    [string[]]
    $Exclude,

    # If set, the generate MAML will not contain a version number.
    # This slightly reduces the size of the MAML file, and reduces the rate of changes in the MAML file.
    [Parameter(ValueFromPipelineByPropertyName=$true)]
    [Alias('Unversioned')]
    [switch]
    $NoVersion,

    # If provided, will save the MAML to a different directory than the current UI culture.
    [Parameter(ValueFromPipelineByPropertyName=$true)]
    [Globalization.CultureInfo]
    $Culture,

    # If set, will return the files that were generated.
    [Parameter(ValueFromPipelineByPropertyName=$true)]
    [switch]
    $PassThru
    )

    process {        
        if ($ScriptName -notlike '*.ps1') { # First, let's check that the scriptname is a .PS1.
            $ScriptName += '.ps1' # If it wasn't, add the extension.
        }

        $Exclude += $ScriptName # Then, add the script name to the list of exclusions.

        if (-not $Culture) { # If no culture was specified,
            $Culture = [Globalization.CultureInfo]::CurrentUICulture # use the current UI culture.
        }

        foreach ($m in $Module) { 
            $theModule = Get-Module $m # Resolve the module.
            if (-not $theModule) { continue }  # If we couldn't, continue to the next.
            $theModuleRoot =  $theModule | Split-Path # Find the module's root.
            
            if ($PSBoundParameters.FunctionRoot) { # If we provided a function root parameter
                $functionRoot = foreach ($f in $FunctionRoot) { # then turn each root into an absolute path.
                    if ([IO.File]::Exists($F)) {
                        $f
                    } else {
                        Join-Path $theModuleRoot $f
                    }
                }
            } else {
                $FunctionRoot = "$theModuleRoot" # otherwise, just use the module root.
            }
            
            $fileList = @(foreach ($f in $FunctionRoot) { # Walk thru each function root.
                Get-ChildItem -Path $f -Recurse:$(-not $Recurse) -Filter *.ps1 | # recursively find all .PS1s
                    & { process {
                        if ($_.Name -notlike '*-*' -or $_.Name -like '*.*.*') { return  }  
                        foreach ($ex in $Exclude) { 
                            if ($_.Name -like $ex) { return } 
                        }
                        return $_
                    } }
            })

            #region Save the MAMLs
            if (-not $NoRefresh) { # If we're refreshing the MAML,
                $saveMamlCmd =  # find the command Save-MAML
                    if ($MyInvocation.MyCommand.ScriptBlock.Module) {
                        $MyInvocation.MyCommand.ScriptBlock.Module.ExportedCommands['Save-MAML']
                    } else {
                        $ExecutionContext.SessionState.InvokeCommand.GetCommand('Save-MAML', 'Function')
                    }
                $saveMamlSplat = @{} + $PSBoundParameters # and pick out the parameters that this function and Save-MAML have in common.
                foreach ($k in @($saveMamlSplat.Keys)) {
                    if (-not $saveMamlCmd.Parameters.ContainsKey($k)) {
                        $saveMamlSplat.Remove($k)
                    }
                }
                $saveMamlSplat.Module = $m # then, set the module
                Save-MAML @saveMamlSplat # and call Save-MAML
            }
            #endregion Save the MAMLs

            #region Generate the Combined Script
            # Prepare a regex to find function definitions.
            $regex = [Regex]::new('
                (?<![-\s\#]{1,}) # not preceeded by a -, or whitespace, or a comment
                function # function keyword
                \s{1,1} # a single space or tab
                (?<Name>[^\-]{1,1}\S+) # any non-whitespace, starting with a non-dash
                \s{0,} # optional whitespace
                [\(\{] # opening parenthesis or brackets
'
, 'MultiLine,IgnoreCase,IgnorePatternWhitespace', '00:00:05')

            
            $newFileContent = # We'll assign new file content by
                foreach ($f in $fileList) { # walking thru each file.
                    $fCmd = $ExecutionContext.SessionState.InvokeCommand.GetCommand($f.FullName, 'ExternalScript')
                    $fileContent = $fCmd.ScriptBlock # and read it as a string.
                    $start = 0
                    do { 
                        $matched = $regex.Match($fileContent,$start) # See if we find a functon.
                        if ($matched.Success) { # If we found one,
                            $insert = ([Environment]::NewLine + "#.ExternalHelp $M-Help.xml" + [Environment]::NewLine) # insert a line for help.
                            $fileContent = if ($matched.Index) {
                                $fileContent.Insert($matched.Index - 1, $insert)
                            } else {
                                $insert + $fileContent
                            }
                            $start += $matched.Index + $matched.Length
                            $start += $insert.Length # and update our starting position.
                        }        
                        # Keep doing this until we've reached the end of the file or the end of the matches.
                    } while ($start -le $filecontent.Length -and $matched.Success) 
  
                    # Then output the file content.
                    $fileContent
                }
            
            # Last but not least, we
            $combinedCommandsPath = Join-Path $theModuleRoot $ScriptName # determine the path for our combined commands file.

            "### DO NOT EDIT THIS FILE DIRECTLY ###" | Set-Content -Path $combinedCommandsPath -Encoding $Encoding.HeaderName.Replace('-','') # add a header
            [IO.File]::AppendAllText($combinedCommandsPath, $newFileContent, $Encoding) # and add our content.
            #endregion Generate the Combined Script

            if ($PassThru) {
                Get-Item -Path $combinedCommandsPath
            }
        }
    }
}
 
#.ExternalHelp HelpOut-Help.xml
function Measure-Help
{
    <#
    .Synopsis
        Determines the percentage of documentation
    .Description
        Determines the percentage of documentation in a given script
    .Example
        dir -Filter *.ps1 | Measure-Help
    .EXAMPLE
        Get-Command -Module HelpOut | Measure-Help
    .Example
        Measure-Help {
            # This script has some documentation, and then a bunch of code that literally does nothing
            $null = $null # The null equivilancy
            $null * 500 # x times nothing is still nothing
            $null / 100 # Nothing out of 100
        } | Select-Object -ExpandProperty PercentageDocumented
    .LINK
        Get-Help
    #>
    
    [CmdletBinding(DefaultParameterSetName='FilePath')]
    param(
    # The path to the file
    [Parameter(Mandatory,ValueFromPipelineByPropertyName,Position=0,ParameterSetName='FilePath')]
    [Alias('Fullname')]
    [string]
    $FilePath,

    # A PowerShell script block
    [Parameter(Mandatory,ParameterSetName='ScriptBlock',ValueFromPipelineByPropertyName)]
    [ScriptBlock]
    $ScriptBlock,

    # The name of the script being measured.
    [Parameter(ParameterSetName='ScriptBlock',ValueFromPipelineByPropertyName)]
    [string]
    $Name
    )

    begin {
        $fileList = New-Object Collections.ArrayList
        $ScriptBlockList = New-Object Collections.ArrayList
        $NameList = New-Object Collections.ArrayList

        filter OutputDocRatio {
            $scriptText = $_
            $scriptToken = [Management.Automation.PSParser]::Tokenize($scriptText, [ref]$null)

            # A quick tight little loop to sum
            # the lengths of different types in one
            # pass (Group-Object would work, but would be slower)
            $commentLength= 0
            $otherLength = 0
            $blockCommentLength = 0
            $inlineCommentLength  = 0
            $blockComments   = @()
            $inlineComments  = @()
            $totalLength = 0 
            foreach ($token in $ScriptToken) {
                $totalLength+=$token.Length
                if ($token.Type -eq 'Comment') {
                    if ($token.Content.StartsWith('<#')) {
                        $blockComments+=$token
                        $blockCommentLength += $token.Length
                    } else {
                        $inlineComments+=$token
                        $inlineCommentLength += $token.Length
                    }
                    $commentLength+=$token.Length
                } else {
                    $otherLength+=$token.Length
                }
            }
        
            # The percent is easy to calculate
            $percent =$commentLength * 100 / $totalLength
            @{
                CommentLength       = $commentLength
                TokenLength         = $otherLength
                CommentPercent      = $percent
                BlockComments       = $blockComments
                BlockCommentLength  = $blockCommentLength
                InlineComments      = $inlineComments
                InlineCommentLength = $inlineCommentLength
            }
            
        }        
    }

    process {
        if ($PSCmdlet.ParameterSetName -eq 'FilePath') {
            $fileList.AddRange(@($FilePath))
        } elseif ($PSCmdlet.ParameterSetName -eq 'ScriptBlock') {
            $null = $ScriptBlockList.Add($ScriptBlock)
            $null = $NameList.Add($Name)
        }
    }

    end {
        if ($ScriptBlockList.Count) {
            $scriptBlockIndex =0 
            foreach ($sb in $ScriptBlockList) {
                [PSCustomObject]([Ordered]@{
                    PSTypeName = "Documentation.Percentage"
                    Name = $NameList[$scriptBlockIndex]
                    ScriptBlock = $sb
                } + ($sb | OutputDocRatio))
                $scriptBlockIndex++
            }
        }

        if ($fileList.Count) {
            foreach ($f in $fileList) {
                $RF = $ExecutionContext.SessionState.Path.GetResolvedPSPathFromPSPath($F)
                if (-not $rf) { continue }
                $fileItem = Get-Item -LiteralPath $RF
                $sb = $null
                $sb = try {
                    [ScriptBlock]::Create([IO.File]::ReadAllText($RF))
                } catch {
                    $null 
                }

                if ($sb) {
                    [PSCustomObject]([Ordered]@{
                        PSTypeName = "File.Documentation.Percentage"
                        Name = $fileItem.Name
                        FilePath = "$rf"
                        ScriptBlock = $sb
                    } + ($sb | OutputDocRatio))
                }
            }
        }
    }
} 
#.ExternalHelp HelpOut-Help.xml
function Save-MAML
{
    <#
    .Synopsis
        Saves a Module's MAML
    .Description
        Generates a Module's MAML file, and then saves it to the appropriate location.
    .Link
        Get-MAML
    .Example
        Save-Maml -Module HelpOut
    .Example
        Save-Maml -Module HelpOut -WhatIf
    .Example
        Save-Maml -Module HelpOut -PassThru
    #>

    [CmdletBinding(DefaultParameterSetName='CommandInfo',SupportsShouldProcess=$true)]
    [OutputType([Nullable], [IO.FileInfo])]
    param( 
    # The name of one or more modules.
    [Parameter(ParameterSetName='ByModule',ValueFromPipelineByPropertyName=$true)]
    [string[]]
    $Module,

    # If set, the generated MAML will be compact (no extra whitespace or indentation). If not set, the MAML will be indented.
    [Parameter(ValueFromPipelineByPropertyName=$true)]
    [switch]
    $Compact,
    
    # If provided, will save the MAML to a different directory than the current UI culture.
    [Parameter(ValueFromPipelineByPropertyName=$true)]
    [Globalization.CultureInfo]
    $Culture,

    # If set, the generate MAML will not contain a version number.
    # This slightly reduces the size of the MAML file, and reduces the rate of changes in the MAML file.
    [Alias('Unversioned')]
    [switch]
    $NoVersion,
    
    # If set, will return the files that were generated.
    [switch]
    $PassThru)

    begin {
        # First, let's cache a reference to Get-MAML
        $getMAML = 
            if ($MyInvocation.MyCommand.ScriptBlock.Module) {
                $MyInvocation.MyCommand.ScriptBlock.Module.ExportedCommands['Get-MAML']
            } else {
                $ExecutionContext.SessionState.InvokeCommand.GetCommand('Get-MAML', 'Function')
            }
    }

    process {
        if (-not $getMAML) { # If for whatever reason we don't have Get-MAML
            Write-Error "Could not Find Get-MAML" -Category ObjectNotFound -ErrorId Get-MAML.NotFound # error out.
            return
        }


        $c, $t, $id = 0, $Module.Length, [Random]::new().Next() 
        $splat = @{} + $PSBoundParameters # Copy our parameters
        foreach ($k in @($splat.Keys)) { # then strip out any parameter
            if (-not $getMAML.Parameters.ContainsKey($k)) { # that wasn't in Get-MAML.
                $splat.Remove($k)
            }
        }

        if (-not $Culture) { # If -Culture wasn't provided, use the current culture
            $Culture = [Globalization.CultureInfo]::CurrentCulture
        }

        #region Save the MAMLs
        foreach ($m in $Module) { # Walk thru the list of module names.
            $splat.Module = $m 
            if ($t -gt 1) {
                $c++
                Write-Progress 'Saving MAML' $m -PercentComplete $p  -Id $id
            }

            $theModule = Get-Module $m # Find the module
            if (-not $theModule) { continue } # (continue if we couldn't).
            $theModuleRoot = $theModule | Split-Path # Find the module's root,
            $theModuleCultureDir = Join-Path $theModuleRoot $Culture.Name # then find the culture folder.

            if (-not (Test-Path $theModuleCultureDir)) { # If that folder didn't exist,
                $null = New-Item -ItemType Directory -Path $theModuleCultureDir # create it.
            }
            
            $theModuleHelpFile = Join-Path $theModuleCultureDir "$m-Help.xml" # Construct the path to the module help file (e.g. en-us\Module-Help.xml)

            & $getMAML @splat | # Convert the module help to MAML,
                Set-Content -Encoding UTF8 -Path $theModuleHelpFile # and write the file.
            
            if ($Passthru) {
                Get-Item -Path $theModuleHelpFile
            }
         }

        if ($t -gt 1) {
            Write-Progress 'Saving MAML' 'Complete' -Completed -Id $id
        }
        #endregion Save the MAMLs
    }
}
 
#.ExternalHelp HelpOut-Help.xml
function Save-MarkdownHelp
{
    <#
    .Synopsis
        Saves a Module's Markdown Help
    .Description
        Get markdown help for each command in a module and saves it to the appropriate location.
    .Link
        Get-MarkdownHelp
    .Example
        Save-MarkdownHelp -Module HelpOut # Save Markdown to HelpOut/docs
    .Example
        Save-MarkdownHelp -Module HelpOut -Wiki # Save Markdown to ../HelpOut.wiki
    #>

    param(
    # The name of one or more modules.
    [Parameter(ParameterSetName='ByModule',ValueFromPipelineByPropertyName=$true)]
    [string[]]
    $Module,

    # The output path.
    # If not provided, will be assumed to be the "docs" folder of a given module (unless -Wiki is specified)
    [Parameter(ValueFromPipelineByPropertyName)]
    [string]
    $OutputPath,

    # If set, will interlink documentation as if it were a wiki. Implied when -OutputPath contains 'wiki'.
    # If provided without -OutputPath, will assume that a wiki resides in a sibling directory of the module.
    [Parameter(ValueFromPipelineByPropertyName)]
    [switch]
    $Wiki,

    # If provided, will generate documentation for additional commands.
    [Parameter(ValueFromPipelineByPropertyName)]
    [Management.Automation.CommandInfo[]]
    $Command,

    # Replaces parts of the names of the commands provided in the -Command parameter.
    # -ReplaceScriptName is treated as a regular expression.
    [Parameter(ValueFromPipelineByPropertyName)]
    [string[]]
    $ReplaceCommandName,

    # If provided, will replace parts of the names of the scripts discovered in a -Command parameter with a given Regex replacement.
    [Parameter(ValueFromPipelineByPropertyName)]
    [string[]]
    $ReplaceCommandNameWith = @(),

    # If provided, will generate documentation for any scripts found within these paths.
    # -ScriptPath can be either a file name or a full path.
    # If an exact match is not found -ScriptPath will also check to see if there is a wildcard match.
    [Parameter(ValueFromPipelineByPropertyName)]
    [string[]]
    $ScriptPath,

    # If provided, will replace parts of the names of the scripts discovered in a -ScriptDirectory beneath a module.
    [Parameter(ValueFromPipelineByPropertyName)]
    [string[]]
    $ReplaceScriptName,

    # If provided, will replace parts of the names of the scripts discovered in a -ScriptDirectory beneath a module with a given Regex replacement.
    [Parameter(ValueFromPipelineByPropertyName)]
    [string[]]
    $ReplaceScriptNameWith = @(),

    # If provided, will replace links discovered in markdown content.
    [Parameter(ValueFromPipelineByPropertyName)]
    [string[]]
    $ReplaceLink,

    # If provided, will replace links discovered in markdown content with a given Regex replacement.
    [Parameter(ValueFromPipelineByPropertyName)]
    [string[]]
    $ReplaceLinkWith = @(),

    # If set, will output changed or created files.
    [switch]
    $PassThru,

    # The order of the sections. If not provided, this will be the order they are defined in the formatter.
    [Parameter(ValueFromPipelineByPropertyName)]
    [string[]]
    $SectionOrder,

    # One or more topic files to include.
    # Topic files will be treated as markdown and directly copied inline.
    # By default ```\.help\.txt$``` and ```\.md$```
    [Parameter(ValueFromPipelineByPropertyName)]
    [string[]]
    $IncludeTopic = @('\.help\.txt$', '\.md$'),

    # One or more topic file patterns to exclude.
    # Topic files that match this pattern will not be included.
    [Parameter(ValueFromPipelineByPropertyName)]
    [string[]]
    $ExcludeTopic = @('\.ps1{0,1}\.md$'),

    # One or more files to exclude.
    # By default, this is treated as a wildcard.
    # If the file name starts and ends with slashes, it will be treated as a Regular Expression.
    [Parameter(ValueFromPipelineByPropertyName)]
    [string[]]
    $ExcludeFile,

    # One or more extensions to include.
    # By default, .css, .gif, .htm, .html, .js, .jpg, .jpeg, .mp4, .png, .svg
    [Parameter(ValueFromPipelineByPropertyName)]
    [string[]]
    $IncludeExtension = @('.css','.gif', '.htm', '.html','.js', '.jpg', '.jpeg', '.mp4', '.png', '.svg'),

    # If set, will not enumerate valid values and enums of parameters.
    [Parameter(ValueFromPipelineByPropertyName)]
    [switch]
    $NoValidValueEnumeration,

    # If set, will not attach a YAML header to the generated help.
    [Parameter(ValueFromPipelineByPropertyName)]
    [Alias('IncludeFrontMatter', 'IncludeHeader')]
    [switch]
    $IncludeYamlHeader,

    # The type of information to include in the YAML Header
    [ValidateSet('Command','Help','Metadata')]
    [Alias('YamlHeaderInfoType')]
    [string[]]
    $YamlHeaderInformationType,

    # A list of command types to skip.
    # If not provided, all types of commands from the module will be saved as a markdown document.
    [Parameter(ValueFromPipelineByPropertyName)]
    [Alias('SkipCommandTypes','ExcludeCommandType','ExcludeCommandTypes')]
    [Management.Automation.CommandTypes[]]
    $SkipCommandType
    )

    begin {
        # First, let's cache a reference to Get-MarkdownHelp
        $GetMarkdownHelp =
            if ($MyInvocation.MyCommand.ScriptBlock.Module) {
                $MyInvocation.MyCommand.ScriptBlock.Module.ExportedCommands['Get-MarkdownHelp']
            } else {
                $ExecutionContext.SessionState.InvokeCommand.GetCommand('Get-MarkdownHelp', 'Function')
            }

        $NotExcluded = {
            if (-not $ExcludeFile) { return $true }
            foreach ($ex in $ExcludeFile) {
                if ($ex -match '^/' -and $ex -match '/$') {
                    if ([Regex]::New(
                        $ex -replace '^/' -replace '/$', 'IgnoreCase,IgnorePatternWhitespace'
                    ).Match($_.FullName)) {
                        return $false
                    }
                } else {
                    if ($_.FullName -like $ex -or $_.Name -like $ex) {
                        return $false
                    }
                }
            }
            return $true
        }

        $filesChanged = @()
    }

    process {
        $getMarkdownHelpSplatBase = @{}

        foreach ($param in $psBoundParameters.Keys) {
            if ($GetMarkdownHelp.Parameters[$param]) {
                $getMarkdownHelpSplatBase[$param] = $psBoundParameters[$param]
            }
        }


        #region Save the Markdowns
        foreach ($m in $Module) { # Walk thru the list of module names.
            if ($t -gt 1) {
                $c++
                Write-Progress 'Saving Markdown' $m -PercentComplete $p  -Id $id
            }

            $theModule = Get-Module $m # Find the module
            if (-not $theModule) { continue } # (continue if we couldn't).
            $theModuleRoot = $theModule | Split-Path # Find the module's root.
            if (-not $psBoundParameters.OutputPath) { # If no -OutputPath was provided
                $OutputPath =
                    if ($Wiki) { # set the default. If it's a wiki, it's a sibling directory
                        Split-Path $theModuleRoot | Join-Path -ChildPath "$($theModule.Name).wiki"
                    } else {
                        Join-Path $theModuleRoot "docs" # Otherwise, it's the docs subdirectory.
                    }
            }

            # If the -OutputPath does not exist
            if (-not (Test-Path $OutputPath)) {
                $null = New-Item -ItemType Directory -Path $OutputPath # create it.
            }

            $outputPathName = $OutputPath | Split-Path -Leaf
            $ReplaceLink   += "^$outputPathName[\\/]"

            # Double-check that the output path
            $outputPathItem = Get-Item $OutputPath
            if ($outputPathItem -isnot [IO.DirectoryInfo]) { # is not a directory
                # (if it is, error out).
                Write-Error "-OutputPath '$outputPath' must point to a directory"
                return
            }

            # Next we're going to call Get-MarkdownHelp on each exported command.
            foreach ($cmd in $theModule.ExportedCommands.Values) {
                # If we specified command types to skip, skip them now.
                if ($SkipCommandType -and $SkipCommandType -contains $cmd.CommandType) {
                    continue
                }

                # Determine the output path for each item.
                $docOutputPath = Join-Path $outputPath ($cmd.Name + '.md')
                # Prepare a splat for this command by copying out base splat.
                $getMarkdownHelpSplat = @{Name="$cmd"} + $getMarkdownHelpSplatBase

                # If -Wiki was passed, call Get-MarkDownHelp with -Wiki (this impacts link format)
                if ($Wiki) { $getMarkdownHelpSplat.Wiki = $Wiki }
                # otherwise, pass down the parent of $OutputPath.
                else { $getMarkdownHelpSplat.GitHubDocRoot = "$($outputPath|Split-Path -Leaf)"}

                & $GetMarkdownHelp @getMarkdownHelpSplat | # Call Get-MarkdownHelp
                    Out-String -Width 1mb                | # output it as a string
                    ForEach-Object { $_.Trim()}          | # trim it
                    Set-Content -Path $docOutputPath -Encoding utf8  # and set the encoding.

                if ($PassThru) { # If -PassThru was provided, get the path.
                    Get-Item -Path $docOutputPath -ErrorAction SilentlyContinue
                }
            }

            if ($Command) {
                foreach ($cmd in $Command) {
                    # For each script that we find, prepare to call Get-MarkdownHelp
                    $getMarkdownHelpSplat = @{
                        Name= if ($cmd.Source) { "$($cmd.Source)" } else { "$cmd" }
                    } + $getMarkdownHelpSplatBase

                    $replacedCmdName =
                        if ($cmd.DisplayName) {
                            $cmd.DisplayName
                        } elseif ($cmd.Name -and $cmd.Name.Contains([IO.Path]::DirectorySeparatorChar)) {
                            $cmd.Name
                        }

                    @(for ($ri = 0; $ri -lt $ReplaceCommandName.Length; $ri++) { # Walk over any -ReplaceScriptName(s) provided.
                        # Replace it with the -ReplaceScriptNameWith parameter (if present).
                        if ($ReplaceCommandNameWith -and $ReplaceCommandNameWith[$ri]) {
                            $replacedCmdName = $replacedCmdName -replace $ReplaceCommandName[$ri], $ReplaceCommandNameWith[$ri]
                        } else {
                            # Otherwise, just remove the replacement.
                            $replacedCmdName = $replacedCmdName -replace $ReplaceCommandName[$ri]
                        }
                    })

                    # Determine the output path for each item.
                    $docOutputPath = Join-Path $outputPath ($replacedCmdName + '.md')
                    $getMarkdownHelpSplat.Rename = $replacedCmdName
                    if ($Wiki) { $getMarkdownHelpSplat.Wiki = $Wiki}
                    else { $getMarkdownHelpSplat.GitHubDocRoot = "$($outputPath|Split-Path -Leaf)"}

                    try {
                        & $GetMarkdownHelp @getMarkdownHelpSplat | # Call Get-MarkdownHelp
                            Out-String -Width 1mb                | # output it as a string
                            ForEach-Object { $_.Trim()}          | # trim it
                            Set-Content -Path $docOutputPath -Encoding utf8  # and set the encoding.
                    }
                    catch {
                        $ex = $_
                        Write-Error -Exception $ex.Exception -Message "Could not Get Help for $($cmd.Name): $($ex.Exception.Message)" -TargetObject $getMarkdownHelpSplat
                    }

                    $filesChanged += # add the file to the changed list.
                        Get-Item -Path $docOutputPath -ErrorAction SilentlyContinue

                    # If -PassThru was provided (and we're not going to change anything)
                    if ($PassThru -and -not $ReplaceLink) {
                        $filesChanged[-1] # output the file changed now.
                    }

                }
            }
            # If a -ScriptPath was provided
            if ($ScriptPath) {
                # get the child items beneath the module root.
                Get-ChildItem -Path $theModuleRoot -Recurse |
                    Where-Object {
                        # Any Script Path whose Name or FullName is
                        foreach ($sp in $ScriptPath) {
                            $_.Name -eq $sp -or     # an exact match,
                            $_.FullName -eq $sp -or
                            $_.Name -like $sp -or   # a wildcard match,
                            $_.FullName -like $sp -or $(
                                $spRegex = $sp -as [regex]
                                $spRegex -and (    # or a regex match
                                    $_.Name -match $spRegex -or
                                    $_.FullName -match $spRegex
                                )
                            )
                        }
                        # will be included.
                    } |
                    # Any child items of that path will also be included
                    Get-ChildItem -Recurse |
                    Where-Object Extension -eq '.ps1' | # (as long as they're PowerShell Scripts).
                    Where-Object $NotExcluded | # (and as long as they're not excluded)
                    ForEach-Object {
                        $ps1File = $_
                        # For each script that we find, prepare to call Get-MarkdownHelp
                        $getMarkdownHelpSplat = @{Name="$($ps1File.FullName)"} + $getMarkdownHelpSplatBase
                        # because not all file names will be valid (or good) topic names
                        $replacedFileName = $ps1File.Name # prepare to replace the file.
                        @(for ($ri = 0; $ri -lt $ReplaceScriptName.Length; $ri++) { # Walk over any -ReplaceScriptName(s) provided.
                            if ($ReplaceScriptNameWith -and $ReplaceScriptNameWith[$ri]) {
                                # Replace it with the -ReplaceScriptNameWith parameter (if present).
                                $replacedFileName = $replacedFileName -replace $ReplaceScriptName[$ri], $ReplaceScriptNameWith[$ri]
                            } else {
                                # Otherwise, just remove the replacement.
                                $replacedFileName = $replacedFileName -replace $ReplaceScriptName[$ri]
                            }
                        })
                        # Determine the output path
                        $docOutputPath = Join-Path $outputPath ($replacedFileName + '.md')
                        # and the relative path of this .ps1 to the module root.
                        $relativePath = $ps1File.FullName.Substring("$theModuleRoot".Length).TrimStart('/\').Replace('\','/')
                        # Then, rename the potential topic with it's relative path.
                        $getMarkdownHelpSplat.Rename = $relativePath
                        if ($Wiki) { $getMarkdownHelpSplat.Wiki = $Wiki}
                        else { $getMarkdownHelpSplat.GitHubDocRoot = "$($outputPath|Split-Path -Leaf)"}
                        # Call Get-MarkdownHelp
                        $markdownHelp = & $GetMarkdownHelp @getMarkdownHelpSplat |
                            Out-String -Width 1mb # format the result

                        if ($markdownHelp) {
                            $markdownHelp.Trim() |
                                Set-Content -Path $docOutputPath -Encoding utf8 # and save it to a file.
                        }


                        $filesChanged += # add the file to the changed list.
                            Get-Item -Path $docOutputPath -ErrorAction SilentlyContinue

                        # If -PassThru was provided (and we're not going to change anything)
                        if ($PassThru -and -not $ReplaceLink) {
                            $filesChanged[-1] # output the file changed now.
                        }
                    }
            }

            # If -IncludeTopic was provided
            if ($IncludeTopic) {
                # get all of the children beneath the module root
                $filesArray = @(Get-ChildItem -Path $theModuleRoot -Recurse -File)
                # then reverse that list, so that the most shallow items come last.
                [array]::reverse($filesArray)
                $filesArray |
                    Where-Object $NotExcluded | # (and as long as they're not excluded)
                    ForEach-Object {
                        $fileInfo = $_
                        # Determine the relative path of the file.
                        $relativePath  =
                            $fileInfo.FullName.Substring("$theModuleRoot".Length) -replace '^[\\/]'
                        # If it is more than one layer deep, ignore it.
                        if ([Regex]::Matches($relativePath, "[\\/]").Count -gt 1) {
                            return
                        }
                        :NextTopicFile foreach ($inc in $IncludeTopic) { # find any files that should be included
                            $matches = $null
                            if ($fileInfo.Name -eq $inc -or
                                $fileInfo.Name -like $inc -or
                                $(
                                    $incRegex = $inc -as [regex]
                                    $incRegex -and $fileInfo.Name -match $incRegex
                                )
                            ) {
                                # Double-check that the file should not excluded.
                                foreach ($exclude in $ExcludeTopic) {
                                    if (
                                        $fileInfo.Name -eq $exclude -or
                                        $fileInfo.Name -like $exclude -or
                                        $(
                                            $exclude -as [regex] -and
                                            $fileInfo.Name -match $exclude
                                        )
                                    ) {
                                        continue NextTopicFile
                                    }
                                }
                                $replacedName =
                                    if ($matches) { # If $inc was a regex
                                        $fileInfo.Name -replace $inc # just replace it
                                    } else {
                                        # Otherwise, strip the file of it's extension
                                        $fileInfo.Name.Substring(0,
                                            $fileInfo.name.Length - $fileInfo.Extension.Length) -replace '\.help$' # (and .help).
                                    }

                                if ($replacedName -eq "about_$module") { # If the replaced named was "about_$Module"
                                    $replacedName = 'README' # treat it as the README
                                }
                                # Determine the output path
                                $dest = Join-Path $OutputPath ($replacedName + '.md')
                                # and make sure we're not overwriting ourselves
                                if ($fileInfo.FullName -ne "$dest") {
                                    $filesChanged += # copy the file and add it to the change list.
                                        $fileInfo | Copy-Item -Destination $dest -PassThru
                                }

                                # If -PassThru was passed and we're not changing anything.
                                if ($PassThru -and -not $ReplaceLink) {
                                    $filesChanged[-1] # output the file now.
                                }
                            }
                        }
                    }
            }

            # If -IncludeExtension was provided
            if ($IncludeExtension) {
                # get all files beneath the root
                Get-ChildItem -Path $theModuleRoot -Recurse -File |
                    Where-Object $NotExcluded | # (and as long as they're not excluded)
                    ForEach-Object {
                        $fileInfo = $_
                        foreach ($ext in $IncludeExtension) { # and see if they are the right extension
                            if ($fileInfo.Extension -eq $ext -or $fileInfo.Extension -eq ".$ext") {
                                # Determine the relative path
                                $relativePath   = $fileInfo.FullName.Substring("$theModuleRoot".Length) -replace '^[\\/]'
                                $outputPathLeaf = $outputPath | Split-Path -Leaf
                                # and use that to determine the destination of this file.
                                $dest = Join-Path $OutputPath $relativePath
                                if ($fileInfo.FullName -ne "$dest" -and
                                    $relativePath -notlike "$outputPathLeaf$([IO.Path]::DirectorySeparatorChar)*") {
                                    # Create the file (so it creates the folder structure).
                                    $createdFile = New-Item -ItemType File -Path $dest -Force
                                    if (-not $createdFile) { # If we could not, write and error and stop trying for this file.
                                        Write-Error "Unable to initialize file: '$dest'"
                                        break
                                    }
                                    # Copy the file to the destination.
                                    if ($fileInfo.FullName -ne "$dest") {
                                        $filesChanged += # and add it to the change list.
                                            $fileInfo | Copy-Item -Destination $dest -PassThru:$PassThru
                                    }

                                    # If -PassThru was passed and we're not changing anything.
                                    if ($PassThru -and -not $ReplaceLink) {
                                        $filesChanged[-1] # output the file now.
                                    }
                                }
                                break
                            }
                        }
                    }
            }
        }

        if ($PassThru -and $ReplaceLink) {
            $linkFinder = [Regex]::new("
            (?<IsImage>\!)? # If there is an exclamation point, then it is an image link
            \[ # Markdown links start with a bracket
            (?<Text>[^\]\r\n]+)
            \] # anything until the end bracket is the link text.
            \( # The link uri is within parenthesis
            (?<Uri>[^\)\r\n]+)
            \)
            "
, 'IgnoreCase,IgnorePatternWhitespace')
            foreach ($file in $filesChanged) {
                if ($file.Extension -notin '.md', '.markdown') {
                    $file
                    continue
                }
                $fileContent = Get-Content $file.FullName -Raw
                $fileContent = $linkFinder.Replace($fileContent, {
                    param($LinkMatch)
                    $linkReplacementNumber = 0

                    $linkUri  = $LinkMatch.Groups["Uri"].ToString()
                    $linkText = $linkMatch.Groups["Text"].ToString()
                    foreach ($linkToReplace in $ReplaceLink) {
                        $replacement = "$($ReplaceLinkWith[$linkReplacementNumber])"
                        $linkUri  = $linkUri  -replace $linkToReplace, $replacement
                        $linkText = $linkText -replace $linkToReplace, $replacement
                    }

                    if ($linkUri -match '\#.+$') {
                        $lowerCaseAnchor = ($matches.0).ToLower()
                        $linkUri = $linkUri -replace '\#.+$', $lowerCaseAnchor
                    }

                    if ($LinkMatch.Groups["IsImage"].Length) {
                        "![$linkText]($linkUri)"
                    } else {
                        "[$linkText]($linkUri)"
                    }
                })

                Set-Content $file.FullName -Encoding UTF8 -Value $fileContent.Trim()

                if ($PassThru) {
                    Get-Item -LiteralPath $file.FullName
                }
            }
        }

        if ($t -gt 1) {
            Write-Progress 'Saving Markdown' 'Complete' -Completed -Id $id
        }
        #endregion Save the Markdowns
    }
}