BAMCIS.FileIO.psm1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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
Function Set-FileSecurity {
    <#
        .SYNOPSIS
            Sets permissions on a file or directory.
 
        .DESCRIPTION
            Will add or replace the supplied rules to the specified file or directory. The default behavior is that the rules are just added to the current ACL of the object.
 
        .PARAMETER Path
            The path to the file to set permissions on.
 
        .PARAMETER Rules
            An array of File Access Rules to apply to the path.
 
        .PARAMETER ReplaceAllRules
            Indictates if all permissions on the path should be replaced with these.
 
        .PARAMETER ReplaceNonInherited
            Replaces all existing rules that are not inherited from a parent directory.
 
        .PARAMETER ReplaceRulesForUser
            Indicates if the supplied rules should replace existing rules for matching users. For example, if the Rules parameter has a Full Control rule for System and a Read rules for
            Administrators, existing rules for System and Administrators would be removed and replaced with the new rules.
 
        .PARAMETER AddIfNotPresent
            Add the rules if they do not already exist on the path. The rules are matched based on all properties including FileSystemRights, PropagationFlags, InheritanceFlags, etc.
 
        .PARAMETER ForceChildInheritance
            Indicates if all permissions of child items should have their permissions replaced with the parent if the target is a directory.
 
        .PARAMETER EnableChildInheritance
            Indicates that child items should have inheritance enabled, but will still preserve existing permissions. This parameter is ignored if ForceChildInheritance is specified.
 
        .PARAMETER ResetInheritance
            Indicates that all explicitly set permissions will be removed from the path and inheritance from its parent will be forced.
 
        .EXAMPLE
            PS C:\>Set-Permissions -Path "c:\test.txt" -Rules $Rules
 
            Creates the rule set on the test.txt file.
 
        .EXAMPLE
            PS C:\>Set-Permissions -Path "c:\test" -ResetInheritance
 
            Resets inherited permissions on the c:\test directory.
 
        .EXAMPLE
            PS C:\>Set-Permissions -Path "c:\test" -Rules $Rules -ReplaceAllRules -ForceChildInheritance
 
            Replaces all existing rules on the c:\test directory with the newly supplied rules and forces child objects to inherit those permissions. This removes existing explicit permissions on child objects.
 
        .INPUTS
            None
 
        .OUTPUTS
            None
 
        .NOTES
            AUTHOR: Michael Haken
            LAST UPDATE: 2/27/2017
    #>


    [CmdletBinding(DefaultParameterSetName = "Add")]
    [Alias("Set-FilePermissions")]
    [OutputType()]
    Param 
    (
        [Parameter(Position=0,Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [System.String]$Path,

        [Parameter(ParameterSetName = "ReplaceAll")]
        [Parameter(ParameterSetName = "Replace")]
        [Parameter(ParameterSetName = "Add")]
        [Parameter(ParameterSetName = "AddIfNotPresent")]
        [Parameter(ParameterSetName = "ReplaceNonInherited")]
        [Parameter(ParameterSetName = "AddIfNotPresentAndReplace")]
        [Alias("Rules")]
        [ValidateNotNull()]
        [System.Security.AccessControl.FileSystemAccessRule[]]$AccessRules,

        [Parameter(ParameterSetName = "ReplaceAll")]
        [Parameter(ParameterSetName = "Replace")]
        [Parameter(ParameterSetName = "Add")]
        [Parameter(ParameterSetName = "AddIfNotPresent")]
        [Parameter(ParameterSetName = "ReplaceNonInherited")]
        [Parameter(ParameterSetName = "AddIfNotPresentAndReplace")]
        [ValidateNotNull()]
        [System.Security.AccessControl.FileSystemAuditRule[]]$AuditRules,

        [Parameter(ParameterSetName = "ReplaceAll")]
        [Switch]$ReplaceAllRules,

        [Parameter(ParameterSetName = "ReplaceNonInherited")]
        [Switch]$ReplaceNonInheritedRules,

        [Parameter(ParameterSetName = "Replace")]
        [Switch]$ReplaceRulesForUser,

        [Parameter(ParameterSetName = "AddIfNotPresent")]
        [Switch]$AddIfNotPresent,

        [Parameter(ParameterSetName = "AddIfNotPresentAndReplace")]
        [Switch]$AddIfNotPresentAndReplace,

        [Parameter()]
        [Switch]$ForceChildInheritance,

        [Parameter()]
        [Switch]$EnableChildInheritance,

        [Parameter(ParameterSetName = "Reset")]
        [Switch]$ResetInheritance
    )

    Begin 
    {           
        Function Convert-FileSystemRights {
            Param(
                [Parameter(Mandatory = $true, Position = 0)]
                [System.Security.AccessControl.FileSystemRights]$Rights
            )

            Begin {
            }

            Process {
                [System.Security.AccessControl.FileSystemRights]$ExistingFileSystemRights = $Rights
                [System.Int32]$Temp = $Rights

                switch ($Temp)
                {
                    #268435456
                    0x10000000 {
                        $ExistingFileSystemRights = [System.Security.AccessControl.FileSystemRights]::FullControl
                        break
                    }
                    #-1610612736
                    0xA0000000 {
                        $ExistingFileSystemRights = @([System.Security.AccessControl.FileSystemRights]::ReadAndExecute, [System.Security.AccessControl.FileSystemRights]::Synchronize)
                        break
                    }
                    #-536805376
                    0xE0010000 {
                        $ExistingFileSystemRights = @([System.Security.AccessControl.FileSystemRights]::Modify, [System.Security.AccessControl.FileSystemRights]::Synchronize)
                        break
                    }
                    default {
                        $ExistingFileSystemRights = $Rights
                        break
                    }
                }

                Write-Output -InputObject $ExistingFileSystemRights
            }

            End {
            }
        }

        Function Get-AuthorizationRuleComparison {
            Param(
                [Parameter(Mandatory = $true, Position = 0)]
                [System.Security.AccessControl.AuthorizationRule]$Rule1,

                [Parameter(Mandatory = $true, Position = 1)]
                [System.Security.AccessControl.AuthorizationRule]$Rule2
            )

            Begin {
            }

            Process {
                $Equal = $false

                try
                {
                    [System.Security.AccessControl.FileSystemRights]$ExistingFileSystemRights1  = Convert-FileSystemRights -Rights $Rule1.FileSystemRights
                    [System.Security.AccessControl.FileSystemRights]$ExistingFileSystemRights2  = Convert-FileSystemRights -Rights $Rule2.FileSystemRights

                    if ($ExistingFileSystemRights1 -eq $ExistingFileSystemRights2 -and `
                        $Rule1.IdentityReference.Translate([System.Security.Principal.SecurityIdentifier]) -eq $Rule2.IdentityReference.Translate([System.Security.Principal.SecurityIdentifier]) -and `
                        $Rule1.AccessControlType -eq $Rule2.AccessControlType -and `
                        $Rule1.InheritanceFlags -eq $Rule2.InheritanceFlags -and `
                        $Rule1.PropagationFlags -eq $Rule2.PropagationFlags)
                    {
                        $Equal = $true
                    }
                }
                catch [Exception]
                {
                    Write-Log -Message "Error evaluating access rule : `nExisting $($Rule1 | FL | Out-String) `nNew $($Rule2 | FL | Out-String)" -ErrorRecord $_ -Level WARNING
                }

                Write-Output -InputObject $Equal
            }

            End {
            }
        }

        Set-TokenPrivilege -Privileges SeSecurityPrivilege -Enable
    }

    Process
    {
        if ($PSCmdlet.ParameterSetName -eq "Add" -and $AccessRules.Length -eq 0 -and $AuditRules.Length -eq 0)
        {
            throw "Either a set of access rules or audit rules must be provided to add to the path."
        }

        Write-Log -Message "Setting access and audit rules on $Path" -Level VERBOSE
        Push-Location -Path $env:SystemDrive

        [System.Boolean]$IsProtectedFromInheritance = $false

        #This is ignored if IsProtectedFromInheritance is false
        [System.Boolean]$PreserveInheritedRules = $false

        try
        {
            #$Acl = Get-Acl -Path $Path
            $Item = Get-Item -Path $Path
            [System.Security.AccessControl.FileSystemSecurity]$Acl = $Item.GetAccessControl(@([System.Security.AccessControl.AccessControlSections]::Access, [System.Security.AccessControl.AccessControlSections]::Audit))

            if ($Acl -ne $null)
            {
                switch ($PSCmdlet.ParameterSetName) {
                    "ReplaceAll" {

                        if ($AccessRules.Length -gt 0)
                        {
                            Write-Log -Message "Disabling access rule inheritance on $Path" -Level VERBOSE
                            $Acl.SetAccessRuleProtection($IsProtectedFromInheritance, $PreserveInheritedRules)

                            [System.Security.AccessControl.AuthorizationRuleCollection]$OldAcls = $Acl.Access

                            foreach ($Rule in $OldAcls)
                            {
                                try 
                                {
                                    $Acl.RemoveAccessRule($Rule) | Out-Null
                                }
                                catch [Exception] 
                                {
                                    Write-Log -Message "Error removing access rule : $($Rule | FL | Out-String)" -ErrorRecord $_ -Level WARNING
                                }
                            }
                        }

                        if ($AuditRules.Length -gt 0)
                        {
                            Write-Log -Message "Disabling audit rule inheritance on $Path" -Level VERBOSE
                            $Acl.SetAuditRuleProtection($IsProtectedFromInheritance, $PreserveInheritedRules)

                            Write-Log -Message "Getting audit rules" -Level VERBOSE
                            [System.Security.AccessControl.AuthorizationRuleCollection]$OldAuditRules = $Acl.GetAuditRules($script:EXPLICIT_TRUE,  $script:INHERITED_FALSE, [System.Security.Principal.NTAccount])

                            foreach ($Rule in $OldAuditRules)
                            {
                                try
                                {
                                    $Acl.RemoveAuditRule($Rule) | Out-Null
                                }
                                catch [Exception]
                                {
                                    Write-Log -Message "Error removing audit rule : $($Rule | FL | Out-String)" -ErrorRecord $_ -Level WARNING
                                }
                            }
                        }

                        break
                    }
                    "ReplaceNonInherited" {

                        if ($AccessRules.Length -gt 0)
                        {
                            [System.Security.AccessControl.AuthorizationRuleCollection]$OldAcls = $Acl.Access

                            foreach ($Rule in ($OldAcls | Where-Object {$_.IsInherited -eq $false}))
                            {
                                try 
                                {
                                    $Acl.RemoveAccessRule($Rule) | Out-Null
                                }
                                catch [Exception] 
                                {
                                    Write-Log -Message "Error removing access rule : $($Rule | FL | Out-String)" -ErrorRecord $_ -Level WARNING
                                }
                            }
                        }

                        if ($AuditRules.Length -gt 0)
                        {
                            Write-Log -Message "Disabling audit rule inheritance on $Path" -Level VERBOSE

                            Write-Log -Message "Getting non inherited audit rules" -Level VERBOSE
                            [System.Security.AccessControl.AuthorizationRuleCollection]$OldAuditRules = $Acl.GetAuditRules($script:EXPLICIT_TRUE,  $script:INHERITED_FALSE, [System.Security.Principal.NTAccount])

                            foreach ($Rule in $OldAuditRules)
                            {
                                try
                                {
                                    $Acl.RemoveAuditRule($Rule) | Out-Null
                                }
                                catch [Exception]
                                {
                                    Write-Log -Message "Error removing audit rule : $($Rule | FL | Out-String)" -ErrorRecord $_ -Level WARNING
                                }
                            }
                        }

                        break
                    }
                    "Replace" {
                        
                        [System.Security.Principal.SecurityIdentifier[]]$Identities = $AccessRules | Select-Object -Property @{Name = "ID"; Expression = { $_.IdentityReference.Translate([System.Security.Principal.SecurityIdentifier]) } } | Select-Object -ExpandProperty ID
                        foreach ($Sid in $Identities)
                        {
                            $Acl.PurgeAccessRules($Sid)
                            $Acl.PurgeAuditRules($Sid)
                        }
                        
                        break
                    }
                    "Add" {
                        #Do Nothing
                        break
                    }
                    "Reset" {
                        [System.Security.AccessControl.AuthorizationRuleCollection]$OldAcls = $Acl.Access

                        foreach ($Rule in $OldAcls)
                        {
                            $Acl.RemoveAccessRule($Rule) | Out-Null
                        }
                
                        $Acl.SetAccessRuleProtection($IsProtectedFromInheritance, $PreserveInheritedRules)            

                        [System.Security.AccessControl.AuthorizationRuleCollection]$OldAuditRules = $Acl.GetAuditRules($script:EXPLICIT_TRUE,  $script:INHERITED_FALSE, [System.Security.Principal.NTAccount])

                        foreach ($Rule in $OldAuditRules)
                        {
                            $Acl.RemoveAuditRule($Rule) | Out-Null
                        }

                        $Acl.SetAuditRuleProtection($IsProtectedFromInheritance, $PreserveInheritedRules)
                        
                        #Call set ACL since no additional rules are provided
                        $Item.SetAccessControl($Acl)
                    }
                    "AddIfNotPresent" {
                        if ($AccessRules.Length -gt 0)
                        {
                            foreach ($Rule in $AccessRules)
                            {
                                [System.Boolean]$Found = $false

                                foreach ($ExistingRule in $Acl.Access)
                                {
                                    $Found = Get-AuthorizationRuleComparison -Rule1 $ExistingRule -Rule2 $Rule
                                    if ($Found -eq $true)
                                    {
                                        Write-Log -Message "Found matching access rule, no need to add this one" -Level VERBOSE
                                        break
                                    }
                                }

                                if ($Found -eq $false)
                                {
                                    try
                                    {
                                        $Acl.AddAccessRule($Rule)
                                    }
                                    catch [Exception]
                                    {
                                        Write-Log -Message "Error adding access rule : $($Rule | FL | Out-String)" -ErrorRecord $_ -Level WARNING
                                    }
                                }
                            }

                            #Call set access control since we've already added the rules
                            $Item.SetAccessControl($Acl)
                        }    

                        if ($AuditRules.Length -gt 0)
                        {
                            foreach ($Rule in $AuditRules)
                            {
                                [System.Boolean]$Found = $false

                                foreach ($ExistingRule in $Acl.GetAuditRules($script:EXPLICIT_TRUE, $script:INHERITED_FALSE, [System.Security.Principal.NTAccount]))
                                {
                                    $Found = Get-AuthorizationRuleComparison -Rule1 $ExistingRule -Rule2 $Rule

                                    if ($Found -eq $true)
                                    {
                                        break
                                    }
                                }

                                if ($Found -eq $false)
                                {
                                    try
                                    {
                                        $Acl.AddAuditRule($Rule)
                                    }
                                    catch [Exception]
                                    {
                                        Write-Log -Message "Error adding audit rule : $($Rule | FL | Out-String)" -ErrorRecord $_ -Level WARNING
                                    }
                                }
                            }
                            #Call set access control since we've already added the rules
                            $Item.SetAccessControl($Acl)
                        }
                        break
                    }
                    "AddIfNotPresentAndReplace" {
                        if ($AccessRules.Length -gt 0)
                        {
                            foreach ($ExistingRule in ($Acl.Access | Where-Object {$_.IsInherited -eq $false }))
                            {
                                [System.Boolean]$Found = $false

                                foreach ($Rule in $AccessRules)
                                {
                                    $Found = Get-AuthorizationRuleComparison -Rule1 $ExistingRule -Rule2 $Rule

                                    #The existing rule did match a new rule
                                    if ($Found -eq $true)
                                    {
                                        break
                                    }
                                }

                                #The existing rule did not match a new rule, remove it
                                if ($Found -eq $false)
                                {
                                    try
                                    {
                                        Write-Log -Message "Removing rule $($Rule | FL | Out-String)" -Level VERBOSE
                                        $Acl.RemoveAccessRule($ExistingRule)
                                    }
                                    catch [Exception]
                                    {
                                        Write-Log -Message "Error removing access rule : $($Rule | FL | Out-String)" -ErrorRecord $_ -Level WARNING
                                    }
                                }
                            }


                            foreach ($Rule in $AccessRules)
                            {
                                [System.Boolean]$Found = $false

                                foreach ($ExistingRule in $Acl.Access)
                                {
                                    $Found = Get-AuthorizationRuleComparison -Rule1 $ExistingRule -Rule2 $Rule

                                    if ($Found -eq $true)
                                    {
                                        break
                                    }
                                }

                                #Did not find a matching, existing rule
                                if ($Found -eq $false)
                                {
                                    try
                                    {
                                        Write-Log -Message "Adding rule $($Rule | FL | Out-String)" -Level VERBOSE
                                        $Acl.AddAccessRule($Rule)
                                    }
                                    catch [Exception]
                                    {
                                        Write-Log -Message "Error adding access rule : $($Rule | FL | Out-String)" -ErrorRecord $_ -Level WARNING 
                                    }
                                }
                            }

                            #Call set access control since we've already added the rules
                            $Item.SetAccessControl($Acl)
                        }    

                        if ($AuditRules.Length -gt 0)
                        {
                            foreach ($ExistingRule in $Acl.GetAuditRules($script:EXPLICIT_TRUE, $script:INHERITED_FALSE, [System.Security.Principal.NTAccount]))
                            {
                                [System.Boolean]$Found = $false

                                foreach ($Rule in $AccessRules)
                                {
                                    $Found = Get-AuthorizationRuleComparison -Rule1 $ExistingRule -Rule2 $Rule

                                    #The existing rule did match a new rule
                                    if ($Found -eq $true)
                                    {
                                        break
                                    }
                                }

                                #The existing rule did not match a new rule, remove it
                                if ($Found -eq $false)
                                {
                                    try
                                    {
                                        Write-Log -Message "Removing rule $($Rule | FL | Out-String)" -Level VERBOSE
                                        $Acl.RemoveAuditRule($ExistingRule)
                                    }
                                    catch [Exception]
                                    {
                                        Write-Log -Message "Error removing audit rule : $($Rule | FL | Out-String)" -ErrorRecord $_ -Level WARNING 
                                    }
                                }
                            }

                            foreach ($Rule in $AuditRules)
                            {
                                [System.Boolean]$Found = $false

                                foreach ($ExistingRule in ($Acl.GetAuditRules($script:EXPLICIT_TRUE, $true, [System.Security.Principal.NTAccount]) | Where-Object {$_.IsInherited -eq $false }))
                                {
                                    $Found = Get-AuthorizationRuleComparison -Rule1 $ExistingRule -Rule2 $Rule

                                    if ($Found -eq $true)
                                    {
                                        break
                                    }
                                }

                                #Did not find a matching, existing rule
                                if ($Found -eq $false)
                                {
                                    try
                                    {
                                        Write-Log -Message "Adding audit rule $($Rule | FL | Out-String)" -Level VERBOSE
                                        $Acl.AddAuditRule($Rule)
                                    }
                                    catch [Exception]
                                    {
                                        Write-Log -Message "Error adding audit rule : $($Rule | FL | Out-String)" -ErrorRecord $_ -Level WARNING
                                    }
                                }
                            }

                            #Call set access control since we've already added the rules
                            $Item.SetAccessControl($Acl)
                        }

                        break
                    }
                    default {
                        throw "Could not determine parameter set name"
                    }
                }
                
                if ($PSCmdlet.ParameterSetName -like "Replace*" -or $PSCmdlet.ParameterSetName -eq "Add")
                {
                    #Add new access rules
                    if($AccessRules.Length -gt 0)
                    {
                        foreach ($Rule in $AccessRules) 
                        {
                            $Acl.AddAccessRule($Rule)
                        }

                        $Item.SetAccessControl($Acl)
                    }

                    #Add new audit rules
                    if ($AuditRules.Length -gt 0)
                    {
                        foreach ($Rule in $AuditRules)
                        {
                            $Acl.AddAuditRule($Rule)
                        }

                        $Item.SetAccessControl($Acl)
                    }    
                }

                #If child permissions should be forced to inherit
                if (($ForceChildInheritance -or $EnableChildInheritance) -and [System.IO.Directory]::Exists($Path))
                {
                    Write-Log -Message "Evaluating child items" -Level VERBOSE
                    Get-ChildItem -Path $Path -Recurse -Force | ForEach-Object {

                        $ChildItem = Get-Item -Path $_.FullName
                        [System.Security.AccessControl.FileSystemSecurity]$ChildAcl = $ChildItem.GetAccessControl(@([System.Security.AccessControl.AccessControlSections]::Access, [System.Security.AccessControl.AccessControlSections]::Audit))

                        if ($AccessRules.Length -gt 0 -or $PSCmdlet.ParameterSetName -eq "Reset")
                        {
                            if ($ForceChildInheritance)
                            {
                                Write-Log -Message "Forcing access rule inheritance on $($ChildItem.FullName)" -Level VERBOSE

                                foreach ($ChildRule in ($ChildAcl.Access | Where-Object {$_.IsInherited -eq $false }))
                                {
                                    try
                                    {
                                        $ChildAcl.RemoveAccessRule($ChildRule) | Out-Null
                                    }
                                    catch [Exception]
                                    {
                                        Write-Log -Message "Error removing ACL from $($ChildItem.FullName)`: $($ChildRule | FL | Out-String)" -ErrorRecord $_ -Level WARNING
                                    }
                                }
                            }

                            try
                            {
                                $ChildAcl.SetAccessRuleProtection($IsProtectedFromInheritance, $PreserveInheritedRules)
                                $ChildItem.SetAccessControl($ChildAcl)
                            }
                            catch [Exception]
                            {
                                Write-Log -Message "Could not set ACL on path $ChildPath." -ErrorRecord $_ -Level WARNING
                            }
                        }

                        if ($AuditRules.Length -gt 0 -or $PSCmdlet.ParameterSetName -eq "Reset")
                        {
                            Write-Log -Message "Forcing audit rule inheritance on $($ChildItem.FullName)" -Level VERBOSE

                            [System.Security.AccessControl.AuthorizationRuleCollection]$OldChildAuditRules = $ChildAcl.GetAuditRules($script:EXPLICIT_TRUE, $script:INHERITED_FALSE, [System.Security.Principal.NTAccount])

                            if ($ForceChildInheritance)
                            {
                                foreach ($ChildAudit in $OldChildAuditRules)
                                {
                                    try
                                    {
                                        $ChildAcl.RemoveAuditRule($ChildAudit) | Out-Null
                                    }
                                    catch [Exception]
                                    {
                                        Write-Log -Message "Error removing audit from $($ChildItem.FullName)`: $($ChildAudit | FL | Out-String)" -ErrorRecord $_ -Level WARNING
                                    }
                                }
                            }

                            try
                            {
                                $ChildAcl.SetAccessRuleProtection($IsProtectedFromInheritance, $PreserveInheritedRules)
                                $ChildItem.SetAccessControl($ChildAcl)
                            }
                            catch [Exception]
                            {
                                Write-Log -Message "Could not set ACL on path $ChildPath." -ErrorRecord $_ -Level WARNING
                            }
                        }
                    }
                }                   
            }
            else
            {
                Write-Log -Message "Could not retrieve the ACL for $Path." -Level WARNING
            }
        }
        catch [System.Exception]
        {
            Write-Log -ErrorRecord $_ -Level WARNING
        }

        Pop-Location
    }
    
    End {
    }
}

Function Set-Owner {
    <#
        .SYNOPSIS
            Changes owner of a file or folder to another user or group.
 
        .DESCRIPTION
            Changes owner of a file or folder to another user or group.
 
        .PARAMETER Path
            The folder or file that will have the owner changed.
 
        .PARAMETER Account
            Optional parameter to change owner of a file or folder to specified account.
 
            Default value is 'Builtin\Administrators'
 
        .PARAMETER Recurse
            Recursively set ownership on subfolders and files beneath given folder. If the specified path is a file, this parameter is ignored.
 
        .EXAMPLE
            PS C:\>Set-Owner -Path C:\temp\test.txt
 
            Changes the owner of test.txt to Builtin\Administrators
 
        .EXAMPLE
            PS C:\>Set-Owner -Path C:\temp\test.txt -Account Domain\user
 
            Changes the owner of test.txt to Domain\user
 
        .EXAMPLE
            PS C:\>Set-Owner -Path C:\temp -Recurse
 
            Changes the owner of all files and folders under C:\Temp to Builtin\Administrators
 
        .EXAMPLE
            PS C:\>Get-ChildItem C:\Temp | Set-Owner -Recurse -Account 'Domain\Administrator'
 
            Changes the owner of all files and folders under C:\Temp to Domain\Administrator
 
        .INPUTS
            None
 
        .OUTPUTS
            None
 
        .NOTES
            AUTHOR: Michael Haken
            LAST UPDATE: 10/23/2017
    #>

    [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = "HIGH")]
    [OutputType()]
    Param (
        [Parameter(Position = 0, ValueFromPipeline = $true, Mandatory = $true)]
        [Alias("FullName")]
        [ValidateScript({
            Test-Path -Path $_
        })]
        [System.String]$Path,

        [Parameter(Position = 1)]
        [ValidateNotNullOrEmpty()]
        [System.String]$Account = 'BUILTIN\Administrators',

        [Parameter()]
        [Switch]$Recurse,

        [Parameter()]
        [Switch]$Force
    )

    Begin {
        if (-not (Test-IsLocalAdmin)) {
            throw "Run the cmdlet with elevated credentials."
        }

        Set-TokenPrivilege -Privileges @("SeRestorePrivilege","SeBackupPrivilege","SeTakeOwnershipPrivilege") -Enable
    }

    Process {
        Write-Log -Message "Set Owner Path: $Path" -Level VERBOSE
        $Account = Get-AccountTranslatedNTName -UserName $Account
        Write-Log -Message "Account Name: $Account" -Level VERBOSE

        #The ACL objects do not like being used more than once, so re-create them on the Process block
        $DirOwner = New-Object System.Security.AccessControl.DirectorySecurity
        $DirOwner.SetOwner((New-Object -TypeName System.Security.Principal.NTAccount($Account)))
        
        $FileOwner = New-Object System.Security.AccessControl.FileSecurity
        $FileOwner.SetOwner((New-Object -TypeName System.Security.Principal.NTAccount($Account)))
        
        try {
            $Item = Get-Item -LiteralPath $Path -Force -ErrorAction Stop

            if (-not $Item.PSIsContainer) 
            {
                $ConfirmMessage = "You are about to change the owner of $($Item.FullName) to $Account."
                $WhatIfDescription = "Set Owner of $($Item.FullName)."
                $ConfirmCaption = "Set File Owner"

                if ($Force -or $PSCmdlet.ShouldProcess($WhatIfDescription, $ConfirmMessage, $ConfirmCaption))
                {
                    $Item.SetAccessControl($FileOwner)
                    Write-Log -Message "Set ownership to $Account on $($Item.FullName)" -Level VERBOSE
                }
            }
            else
            {
                $ConfirmMessage = "You are about to change the owner of $($Item.FullName) to $Account."
                $WhatIfDescription = "Set Owner of $($Item.FullName)."
                $ConfirmCaption = "Set Directory Owner"

                if ($Force -or $PSCmdlet.ShouldProcess($WhatIfDescription, $ConfirmMessage, $ConfirmCaption))
                {
                    $Item.SetAccessControl($DirOwner)
                    Write-Log -Message "Set ownership to $Account on $($Item.FullName)" -Level VERBOSE
                }

                if ($Recurse) 
                {
                    Get-ChildItem $Item -Force -Recurse | ForEach-Object {
                        Set-Owner -Path $_.FullName -Account $Account -Force
                    }
                }
            }
        }
        catch [Exception] {
            Write-Log -Message "Failed to set owner on $($Item.FullName)" -ErrorRecord $_ -Level WARNING
        }
    }

    End {
        Set-TokenPrivilege -Privileges @("SeRestorePrivilege","SeBackupPrivilege","SeTakeOwnershipPrivilege") -Disable
    }
}

Function Invoke-ForceDelete {
    <#
        .SYNOPSIS
            The cmdlet forces the deletion of a file or folder and all of its content.
 
        .DESCRIPTION
            The cmdlet takes ownership of the file or content in a directory and grants the current user
            full control permissions to the item. Then it deletes the item and performs this recursively
            through the directory structure specified.
         
        .PARAMETER Path
            The path to the file or folder to forcefully delete.
 
        .PARAMETER Force
            Ignores the confirmation to delete each item.
 
        .INPUTS
            System.String
         
        .OUTPUTS
            None
 
        .EXAMPLE
            Invoke-ForceDelete -Path c:\windows.old
 
            Forcefully deletes the c:\windows.old directory and all of its content.
 
        .NOTES
            AUTHOR: Michael Haken
            LAST UPDATE: 4/24/2017
    #>

    [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = "HIGH")]
    [OutputType()]
    Param(
        [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)]
        [ValidateNotNullOrEmpty()]
        [ValidateScript({ 
            try {
               Test-Path -Path $_ -ErrorAction Stop
            }
            catch [System.UnauthorizedAccessException] {
                $true
            } 
        })]
        [System.String]$Path,

        [Parameter()]
        [Switch]$Force
    )

    Begin {
    }

    Process {    
        # Fix any paths that were fed in dot sourced
        $Path = Resolve-Path -Path $Path
        $IsDir = [System.IO.Directory]::Exists($Path)

        Write-Log -Message "Invoke-ForceDelete cmdlet called with path $Path." -Level VERBOSE

        [System.String]$UserName = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
        $UserName = Get-AccountTranslatedNTName -UserName $UserName

        # Take ownership of the provided path
        Set-Owner -Path $Path -Account $UserName -Recurse -Force

        # Full Control to "This folder, subfolders, and files"
        [System.Security.Principal.NTAccount]$NTAccount = New-Object -TypeName System.Security.Principal.NTAccount($UserName)
        [System.Security.Principal.SecurityIdentifier]$Sid = $NTAccount.Translate([System.Security.Principal.SecurityIdentifier])
        
        if ($IsDir)
        {
            $Ace = New-Object System.Security.AccessControl.FileSystemAccessRule($Sid,
                [System.Security.AccessControl.FileSystemRights]::FullControl,
                ([System.Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [System.Security.AccessControl.InheritanceFlags]::ObjectInherit),
                [System.Security.AccessControl.PropagationFlags]::None,
                [System.Security.AccessControl.AccessControlType]::Allow       
            )
        }
        else
        {
            $Ace = New-Object System.Security.AccessControl.FileSystemAccessRule($Sid,
                [System.Security.AccessControl.FileSystemRights]::FullControl,
                [System.Security.AccessControl.InheritanceFlags]::None,
                [System.Security.AccessControl.PropagationFlags]::None,
                [System.Security.AccessControl.AccessControlType]::Allow       
            )
        }

        Set-FileSecurity -Path $Path -AccessRules $Ace -ForceChildInheritance

        # If it's a directory, remove all of the child content
        if ($IsDir)
        {
            Write-Log -Message "The current path $Path is a directory." -Level VERBOSE

            Get-ChildItem -Path $Path -Force | ForEach-Object {         
                Invoke-ForceDelete -Path $_.FullName -Force
            }
        }
        
        # Remove the specified path whether it is a folder or file
        try
        {    
            $ConfirmMessage = "You are about to force delete $Path."
            $WhatIfDescription = "Deleted $Path."
            $ConfirmCaption = "Force Delete"

            if ($Force -or $PSCmdlet.ShouldProcess($WhatIfDescription, $ConfirmMessage, $ConfirmCaption))
            {
                Write-Log -Message "Deleting $Path" -Level VERBOSE
                Remove-Item -Path $Path -Confirm:$false -Force -Recurse

                $Counter = 0

                do 
                {
                    try {
                        $Found = Test-Path -Path $Path -ErrorAction Stop
                    }
                    catch [System.UnauthorizedAccessException] {
                        $Found = $true
                    }

                    Start-Sleep -Milliseconds 100
                
                } while (($Found -eq $true) -and $Counter++ -lt 50)

                if ($Counter -eq 50)
                {
                    Write-Log -Message "Timeout waiting for $Path to delete" -Level WARNING
                }
            }
        }
        catch [Exception]
        {
            Write-Log -ErrorRecord $_ -Level WARNING
        }      
    }

    End {
    }
}

Function Rename-FileOrDirectory {
    <#
        .SYNOPSIS
            The cmdlet renames a file or directory and uses an incrementing counter appended to the desired filename if it already exists.
 
        .DESCRIPTION
            The cmdlet attempts to rename a file with the specified new name. If the new name already exists, the postfix "(#)" is added before the file extension,
            or the end of the directory name, where "#" is a number starting from 1 and incrementing by 1 until the new name is unique in the directory.
 
        .PARAMETER Path
            The file or directory to rename.
 
        .PARAMETER NewName
            The new name of the file or directory. Use a literal, not relative, path.
 
        .PARAMETER Credential
            The credential to use to perform the operation.
 
        .EXAMPLE
            Rename-FileOrDirectory -Path c:\temp\file1.txt -NewName c:\temp\file2.txt -PassThru
 
            In this example the file c:\temp\file2.txt and c:\temp\file2(1).txt already exists. The file c:\temp\file1.txt is renamed to
            c:\temp\file2(2).txt and the file info about its resulting name is returned to the pipeline.
 
        .INPUTS
            System.String
 
        .OUTPUTS
            None or System.IO.DirectoryInfo or System.IO.FileInfo
 
        .NOTES
            AUTHOR: Michael Haken
            LAST UPDATE: 10/23/2017
    #>

    [CmdletBinding()]
    [OutputType([System.IO.FileInfo], [System.IO.DirectoryInfo])]
    Param(
        [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)]
        [ValidateScript({
            Test-Path -Path $_
        })]
        [ValidateNotNullOrEmpty()]
        [System.String]$Path,

        [Parameter(Mandatory = $true, Position = 1)]
        [ValidateNotNullOrEmpty()]
        [System.String]$NewName,

        [Parameter()]
        [Switch]$Force,

        [Parameter()]
        [ValidateNotNull()]
        [System.Management.Automation.Credential()]
        [System.Management.Automation.PSCredential]$Credential = [System.Management.Automation.PSCredential]::Empty,

        [Parameter()]
        [Switch]$PassThru
    )

    Begin{
    }

    Process {
        [System.IO.FileInfo]$Info = New-Object -TypeName System.IO.FileInfo($Path)
        $Base = $Info.DirectoryName
        $Name = $Info.BaseName
        $Ext = $Info.Extension

        $Counter = 1

        while (Test-Path -Path $NewName)
        {
            $NewName = "$Base\$Name($Counter)$Ext"
            $Counter++
        }

        [System.Collections.Hashtable]$Splat = @{}

        if ($Force)
        {
            $Splat.Add("Force", $true)
        }

        if ($Credential -ne [System.Management.Automation.PSCredential]::Empty)
        {
            $Splat.Add("Credential", $Credential)
        }

        if ($PassThru)
        {
            $Splat.Add("PassThru", $true)
        }

        Rename-Item -Path $Path -NewName $NewName @Splat
    }

    End {
    }
}

Function Get-FileVersion {
    <#
        .SYNOPSIS
            Gets the version of a specific file or file running a Windows service from its metadata.
 
        .DESCRIPTION
            This cmdlet gets the FileVersion data from a specified file or file running a service. If no version is included in the FileInfo, the cmdlet returns "0".
 
        .PARAMETER Path
            The path to the file.
 
        .PARAMETER Service
            The name of the service.
 
        .INPUTS
            None
 
        .OUTPUTS
            System.String
 
        .EXAMPLE
            Get-FileVersion -Path "c:\installer.exe"
 
            Gets the file version of installer.exe.
 
        .EXAMPLE
            Get-FileVersion -Service lmhosts
 
            Gets the file version of the svchost.exe running the lmhosts service.
 
        .NOTES
            AUTHOR: Michael Haken
            LAST UPDATE: 8/24/2016
    #>

    [CmdletBinding()]
    [OutputType([System.String])]
    Param(
        [Parameter(Mandatory = $true, ParameterSetName = "File", ValueFromPipeline = $true, Position = 0)]
        [ValidateScript({
            Test-Path -Path $_
        })]
        [System.String]$Path
    )

    DynamicParam
    {
        [System.Management.Automation.RuntimeDefinedParameterDictionary]$ParamDictionary = New-Object -TypeName System.Management.Automation.RuntimeDefinedParameterDictionary

        $Services = Get-Service | Select-Object -ExpandProperty Name
        New-DynamicParameter -Name "ServiceName" -ParameterSets "Service" -Type ([System.String]) -Mandatory -ValueFromPipeline -Position 0 -ValidateSet $Services -RuntimeParameterDictionary $ParamDictionary | Out-Null

        return $ParamDictionary
    }

    Begin {
    }

    Process {
        switch ($PSCmdlet.ParameterSetName) {
            "File" {
                break
            }
            "Service" {
                $Path = (Get-WmiObject -Class Win32_Service -Filter "Name = `"$($PSBoundParameters.ServiceName)`"" | Select-Object -ExpandProperty PathName).Trim("`"")
                break
            }
            default {
                Write-Log -Message "Could not determine parameter set name from given parameters." -Level FATAL
            }
        }

        $Version = New-Object -TypeName System.IO.FileInfo($Path) | Select-Object -ExpandProperty VersionInfo | Select-Object -ExpandProperty FileVersion

        if ([System.String]::IsNullOrEmpty($Version))
        {
            $Version = "0"
        }

        Write-Output -InputObject $Version
    }

    End {    
    }
}

Function Invoke-ExtractZip {
    <#
        .SYNOPSIS
            The cmdlet extracts the contents of a zip file to a specified destination.
 
        .DESCRIPTION
            The cmdlet extracts the contents of a zip file to a specified destination and optionally preserves the contents in the destination if they already exist.
 
        .PARAMETER Source
            The path to the zip file.
 
        .PARAMETER Destination
            The folder where the zip file should be extracted. The destination is created if it does not already exist.
 
        .PARAMETER NoOverwrite
            Specify if the contents in the destination should be preserved if they already exist.
 
        .PARAMETER OverwriteIfNewer
            Only overwrite existing files if the file in the zip is newer (by last modification date) than the existing file.
 
        .INPUTS
            None
         
        .OUTPUTS
            None
 
        .EXAMPLE
            Invoke-ExtractZip -Source "c:\test.zip" -Destination "c:\test"
 
            Extracts the contents of test.zip to c:\test.
 
        .NOTES
            AUTHOR: Michael Haken
            LAST UPDATE: 10/27/2017
    #>

    [CmdletBinding(DefaultParameterSetName = "Overwrite")]
    [OutputType()]
    Param(
        [Parameter(Position = 0, Mandatory = $true)]
        [ValidateScript({
            Test-Path -Path $_
        })]
        [System.String]$Source,

        [Parameter(Position = 1, Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [System.String]$Destination,

        [Parameter(ParameterSetName = "No")]
        [Switch]$NoOverwrite,

        [Parameter(ParameterSetName = "Newer")]
        [Switch]$OverwriteIfNewer
    )

    Begin {
        Add-Type -AssemblyName System.IO.Compression.FileSystem
    }

    Process {
        if (!(Test-Path -Path $Source)) {
            throw (New-Object -TypeName System.IO.FileNotFoundException("Source zip file not found."))
        }

        if (-not (Test-Path -Path $Destination)) {

            Write-Log -Message "Zip extract destination $Destination does not exist, creating it."

            try {
                New-Item -Path $Destination -ItemType Directory | Out-Null

                $Counter = 0

                while (!(Test-Path -Path $Destination)) {
                    Start-Sleep -Seconds 1
                    $Counter++

                    if ($Counter -gt 60) {
                        throw "Timeout error waiting for the zip extraction destination $Destination to be created."
                    }
                }
            }
            catch [Exception] {
                Write-Log -ErrorRecord $_ -Level FATAL
            }
        }
        else {
            if ([System.IO.File]::Exists($Destination)) {
                throw (New-Object -TypeName System.IO.DirectoryNotFoundException("The destination is a file, not a directory."))
            }
        }

        [System.IO.Compression.ZipArchive]$ZipArchive = [System.IO.Compression.ZipFile]::OpenRead($Source)
            
        try
        {
            foreach ($ZipArchiveEntry in $ZipArchive.Entries) 
            {
                $FullPath = [System.IO.Path]::Combine($Destination, $ZipArchiveEntry.FullName)
                [System.String]$Directory = [System.IO.Path]::GetDirectoryName($FullPath)
                
                if (-not [System.IO.Directory]::Exists($Directory))
                {
                    [System.IO.Directory]::CreateDirectory($Directory)
                }

                Write-Log -Message "Evaluating $($ZipArchiveEntry.FullName) to unzip to $FullPath." -Level VERBOSE

                # If we don't want to overwrite existing files, check to see if the path exists
                if ($NoOverwrite)
                {
                    # If it doesn't exist, we'll extract
                    if (-not (Test-Path -Path $FullPath))
                    {
                        # To handle the race condition of extracting it and the file could have been created before the extraction occurs
                        # catch the IOException and check to see if it's because the file already exists, if it is, ignore the exception, otherwise,
                        # throw the exception
                        try
                        {
                            [System.IO.Compression.ZipFileExtensions]::ExtractToFile($ZipArchiveEntry, $FullPath)
                        }
                        catch [System.IO.IOException]
                        {
                            if ($_.Exception.Message -inotlike "*already exists.")
                            {
                                throw $_.Exception
                            }
                        }
                    }
                }
                else
                {
                    # If we are overwriting files, but only want to overwrite if the zip file is newer, check to see if it exists
                    if ($OverwriteIfNewer)
                    {
                        # If the file exists, check the last modified times
                        if (Test-Path -Path $FullPath)
                        {
                            if ((New-Object -TypeName System.IO.FileInfo($FullPath)).LastWriteTimeUtc -lt $ZipArchiveEntry.LastWriteTime.ToUniversalTime().Date)
                            {
                                Write-Log -Message "Overwriting zip output $FullPath with newer file." -Level VERBOSE
                                [System.IO.Compression.ZipFileExtensions]::ExtractToFile($ZipArchiveEntry, $FullPath, $true)
                            }
                        }
                        else
                        {
                            [System.IO.Compression.ZipFileExtensions]::ExtractToFile($ZipArchiveEntry, $FullPath, $true)
                        }
                    }
                    else
                    {
                        [System.IO.Compression.ZipFileExtensions]::ExtractToFile($ZipArchiveEntry, $FullPath, $true)
                    }
                }
            }
        }
        catch [Exception]
        {
            Write-Log -ErrorRecord $_ -Level FATAL
        }
        finally
        {
            $ZipArchive.Dispose()
        }
    }

    End {        
    }
}

Function Invoke-ExtractGZip {
    <#
        .SYNOPSIS
            The cmdlet extracts the contents of a gzip file to a specified destination.
 
        .DESCRIPTION
            The cmdlet first examines the gzip file to see if it contains concatenated files. If it does, it separates those chunks and decompresses each chunk to its
            own file, or if specified, to the same file. If the contents are each written to their own file, each file is written to the destination directory using
            a "(#)" post fix for each file after the first. The decompressed files will not use an extension, or can optionally use an extension you specify
 
        .PARAMETER Source
            The path to the gzip file.
 
        .PARAMETER Destination
            The folder where the gzip file should be extracted. The destination is created if it does not already exist.
 
        .PARAMETER CreateSingleFile
            Creates a single file in case the gzip contains concatenated gzip files. If this is not specified and the gzip contains concatenated files, each
            concatenated file it written to its own output file.
 
        .PARAMETER NoOverwrite
            Specify this to not overwrite an existing file in the destination directory.
 
        .PARAMETER Extension
            The extension to use on the decompressed files. If this is not specified, any extension contained in the filename is used. For example, if the
            input source is file.json.gz, the extension on the output is .json since the .gz is stripped off. If you provided "txt" as the extension, the output
            file would be file.json.txt.
 
        .INPUTS
            System.String
         
        .OUTPUTS
            None or System.IO.FileInfo[]
 
        .EXAMPLE
            Invoke-ExtractGZip -Source "c:\test.gz" -Destination "c:\test" -Extension "txt"
 
            Extracts the contents of test.gzip to c:\test\test.txt
 
        .EXAMPLE
            Invoke-ExtractGZip -Source "c:\test.json.gz" -Destination "c:\test"
 
            In this example, the gzip contains 2 concatenated files. The output is:
 
            c:\test\test.json
            c:\test\test(1).json
 
        .EXAMPLE
            Invoke-ExtractGZip -Source "c:\test.json.gz" -Destination "c:\test" -CreateSingleFile
 
            In this example, the gzip contains 2 concatenated files, but the contents of both files are output to a single file, c:\test\test.json.
         
            As a note, the resulting json file would not be well-formatted since it contains to JSON objects not inside an array.
 
        .NOTES
            AUTHOR: Michael Haken
            LAST UPDATE: 10/27/2017
    #>

    [CmdletBinding()]
    [OutputType([System.IO.FileInfo[]])]
    Param(
        [Parameter(Position = 0, Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [ValidateScript({
            Test-Path -Path $_
        })]
        [System.String]$Source,

        [Parameter(Position = 1, Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNullOrEmpty()]
        [System.String]$Destination,

        [Parameter()]
        [Switch]$NoOverwrite,

        [Parameter()]
        [Switch]$CreateSingleFile,

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [System.String]$Extension,

        [Parameter()]
        [Switch]$PassThru
    )

    Begin {
        Add-Type -AssemblyName System.IO.Compression.FileSystem
    }

    Process {
        [System.Byte[]]$FileBytes = [System.IO.File]::ReadAllBytes($Source)
        [System.Int32[]]$StartIndexes = @()
        
        # This pattern indicates the start of a GZip file as found from looking at the files
        # The file header is 10 bytes in size
        # 0-1 Signature 0x1F, 0x8B
        # 2 Compression Method - 0x08 is for DEFLATE, 0-7 are reserved
        # 3 Flags
        # 4-7 Last Modification Time
        # 8 Compression Flags
        # 9 Operating System
        
        [System.Byte[]]$StartOfFilePattern = [System.Byte[]](0x1F, 0x8B, 0x08)

        # This will limit the last byte we check to make sure it doesn't exceed the end of the file
        # If the file is 100 bytes and the file pattern is 10 bytes, the last byte we want to check is
        # 90 -> i.e. we will check index 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 and index 99 is the last
        # index in the file bytes
        [System.Int64]$TraversableLength = $FileBytes.LongLength - $StartOfFilePattern.LongLength

        for ($i = 0; $i -le $TraversableLength; $i++)
        {
            [System.Boolean]$Match = $true

            # Test the next run of characters to see if they match
            for ($j = 0; $j -lt $StartOfFilePattern.Length; $j++)
            {
                # If the character doesn't match, break out
                # We're making sure that i + j doesn't exceed the length as part
                # of the loop bounds
                if ($FileBytes[$i + $j] -ne $StartOfFilePattern[$j])
                {
                    $Match = $false
                    break
                }
            }

            # If we did find a run of matching bytes
            if ($Match -eq $true)
            {
                $StartIndexes += $i
                # Since we had a match, move the index ahead the length of the start of file pattern
                # Then the for loop will add 1 to move to the next index
                $i += $StartOfFilePattern.Length
            }
        }

        # In case the pattern doesn't match, just start from the beginning of the file
        if ($StartIndexes.Count -eq 0)
        {
            $StartIndexes += 0
        }

        [System.Collections.Generic.List[System.Byte[]]]$Chunks = New-Object -TypeName System.Collections.Generic.List[System.Byte[]]

        for ($i = 0; $i -lt $StartIndexes.Count; $i++)
        {
            [System.Int32]$Start = $StartIndexes[$i]

            [System.Int32]$Length = 0

            # If this index is the last index, take the rest of the file bytes
            if ($i + 1 -eq $StartIndexes.Count)
            {
                $Length = $FileBytes.Length - $Start
            }
            # Otherwise take the chunk from this start to the next one
            else
            {
                # The length to read is the next start index minus the current start index
                $Length = $StartIndexes[$i + 1] - $StartIndexes[$i]
            }

            if ($Length -gt 0)
            {
                $Chunks.Add(($FileBytes | Select-Object -Skip $Start -First $Length))
            }
        }

        [System.IO.MemoryStream]$MStreamOut = New-Object -TypeName System.IO.MemoryStream
        [System.IO.FileInfo]$Info = New-Object -TypeName System.IO.FileInfo($Source)
        [System.Int32]$Counter = 0

        if (-not [System.String]::IsNullOrEmpty($Extension))
        {
            if ($Extension.StartsWith("."))
            {
                $Extension = $Extension.Substring(1)
            }
        }

        if (-not $CreateSingleFile)
        {
            [System.String]$BaseName = $Info.BaseName

            if ([System.String]::IsNullOrEmpty($Extension))
            {
                if ($BaseName.Contains("."))
                {
                    $Extension = $BaseName.Substring($BaseName.IndexOf(".") + 1)
                    $BaseName = $BaseName.Substring(0, $BaseName.IndexOf("."))
                }
            }
        }
        
        [System.IO.FileInfo[]]$Results = @()

        try
        {
            foreach ($Chunk in $Chunks)
            {
                [System.IO.MemoryStream]$MStream = New-Object -TypeName System.IO.MemoryStream(,$Chunk)

                try
                {
                    [System.IO.Compression.GZipStream]$GZStream = New-Object -TypeName System.IO.Compression.GZipStream($MStream, [System.IO.Compression.CompressionMode]::Decompress)
                
                    try
                    {
                        $GZStream.CopyTo($MStreamOut)

                        if (-not $CreateSingleFile)
                        {        
                            [System.String]$FileName = [System.IO.Path]::Combine($Destination, "$BaseName$(if ($Counter -gt 0) {"($Counter)"})$(if (-not [System.String]::IsNullOrEmpty($Extension)) { ".$Extension" })")                            
                            $Counter++

                            [System.IO.File]::WriteAllBytes($FileName, $MStreamOut.ToArray())
                            $Results += (Get-Item -Path $FileName)

                            # Reset the output memory stream
                            $MStreamOut.SetLength(0)
                        }
                    }
                    finally
                    {
                        $GZStream.Dispose()
                    }
                }
                finally
                {
                    $MStream.Dispose()
                }
            }
                
            if ($CreateSingleFile)
            {
                $FileName = [System.IO.Path]::Combine($Destination, "$($Info.BaseName)$(if (-not [System.String]::IsNullOrEmpty($Extension)) {".$Extension"})")
                [System.IO.File]::WriteAllBytes($FileName, $MStreamOut.ToArray())
                $Results += (Get-Item -Path $FileName)
            }
        }
        finally
        {
            $MStreamOut.Dispose()
        }

        if ($PassThru)
        {
            Write-Output -InputObject $Results
        }
    }

    End {
    }
}

Function New-ISO {
    <#
        .SYNOPSIS
            Creates a new ISO image from the specified content.
 
        .DESCRIPTION
            This cmdlet creates in ISO image file containing specified content. It can also be used to make a bootable ISO with something like WinPE.
 
        .PARAMETER Content
            The FileInfo, DirectoryInfo, or string Path names of the files and folders to include in the ISO. Each item will be added to the root of the ISO file system tree.
 
        .PARAMETER Destination
            The location the ISO file will be created and written to. Use -Force to overwrite an existing file.
 
        .PARAMETER BootFile
            The path to a boot file. For example c:\Program Files (X86)\Windows Kits\10\Assessment and Deployment Kit\Deployment Tools\amd64\Oscdimg\efisys.bin".
 
        .PARAMETER Media
            The media type to emulate with the ISO. This defaults to DVDPLUSRW_DUALLAYER.
 
        .PARAMETER Title
            The title of the ISO image file.
 
        .EXAMPLE
            New-ISO -Content c:\users\john.smith\Desktop -Destination c:\users\john.smith\desktop\backup.iso
 
            This creates a new ISO image file on the user's desktop containing the desktop folder at the root of the ISO with all of its contents inside.
 
        .EXAMPLE
            Get-ChildItem -Path c:\users\john.smith\Desktop | New-ISO -Destination c:\users\john.smith\desktop\backup.iso
 
            This creates a new ISO image file on the user's desktop containing the contents of the desktop folder at the root of the ISO.
 
        .EXAMPLE
            Get-ChildItem -Path c:\WinPE | New-ISO -Destination c:\temp\WinPE.iso -BootFile "$env:ProgramFiles(x86)\Windows Kits\10\Assessment and Deployment Kit\Deployment Tools\amd64\Oscdimg\efisys.bin" -Media DVDPLUSR -Title "WinPE"
 
            This creates a bootable ISO from WinPE and includes the contents of the c:\WinPE folder in the image.
 
        .INPUT
            System.Object[]
 
        .OUTPUT
            System.IO.FileInfo
 
        .NOTES
            AUTHOR: Michael Haken
            LAST UPDATE: 2/23/2019
    #>


    [CmdletBinding(DefaultParameterSetName = "Content")]
    Param(
        [Parameter(Mandatory = $true, Position = 0, ParameterSetName = "Content", ValueFromPipeline = $true)]
        [ValidateNotNullOrEmpty()]
        [System.Object[]]$Content,

        [Parameter(Mandatory = $true, Position = 1)]
        [ValidateNotNullOrEmpty()]
        [System.String]$Destination,

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [ValidateScript({
            Test-Path -Path $_
        })]
        [System.String]$BootFile = [System.String]::Empty,

        [Parameter()]
        [ValidateSet("CDR","CDRW","DVDRAM","DVDPLUSR","DVDPLUSRW","DVDPLUSR_DUALLAYER","DVDDASHR","DVDDASHRW","DVDDASHR_DUALLAYER","DISK","DVDPLUSRW_DUALLAYER","BDR","BDRE")]
        [System.String]$Media = "DVDPLUSRW_DUALLAYER",

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [System.String]$Title = ([System.DateTime]::UtcNow.ToString("yyyy-mm-ddThh:mm:ss.fff")),

        [Parameter()]
        [Switch]$Force
    )

    Begin {
        if (-not [System.String]::IsNullOrEmpty($BootFile)) 
        {       
            if (@("BDR","BDRE") -contains $Media) 
            { 
                throw "Bootable image doesn't work with media type $Media." 
            } 

            $BootFileName = Get-Item -LiteralPath $BootFile | Select-Object -ExpandProperty FullName
            $Stream = New-Object -ComObject ADODB.Stream -Property @{Type = 1}
            $Stream.Open()
            $Stream.LoadFromFile($BootFileName)
            $BootOptions = New-Object -ComObject IMAPI2FS.BootOptions
            $BootOptions.AssignBootImage($Stream)
        }
        
        if (([System.AppDomain]::CurrentDomain.GetAssemblies() | 
            Where-Object { -not [System.String]::IsNullOrEmpty($_.Location) } | 
            Select-Object -Property @{Name = "Type"; Expression = {$_.GetTypes()}} |
            Select-Object -ExpandProperty Type |
            Where-Object { $_.FullName -eq "BAMCIS.FileIO.ISO.IMAPI_MEDIA_PHYSICAL_TYPE" }).Count -eq 0)
        {
            # The members are prefaced with IMAPI_MEDIA_TYPE_ in the real enum
            Add-Type -TypeDefinition @"
namespace BAMCIS.FileIO.ISO
{
    public enum IMAPI_MEDIA_PHYSICAL_TYPE
    {
        UNKNOWN,
        CDROM,
        CDR,
        CDRW,
        DVDROM,
        DVDRAM,
        DVDPLUSR,
        DVDPLUSRW,
        DVDPLUSR_DUALLAYER,
        DVDDASHR,
        DVDDASHRW,
        DVDDASHR_DUALLAYER,
        DISK,
        DVDPLUSRW_DUALLAYER,
        HDDVDROM,
        HDDVDR,
        HDDVDRAM,
        BDROM,
        BDR,
        BDRE,
        MAX
    }
}
"@

        }

        
        if (([System.AppDomain]::CurrentDomain.GetAssemblies() | 
            Where-Object { -not [System.String]::IsNullOrEmpty($_.Location) } | 
            Select-Object -Property @{Name = "Type"; Expression = {$_.GetTypes()}} |
            Select-Object -ExpandProperty Type |
            Where-Object { $_.FullName -eq "BAMCIS.FileIO.ISO.ISOFile" }).Count -eq 0)
        {
            [System.CodeDom.Compiler.CompilerParameters]$CompilerParameters = New-Object -TypeName System.CodeDom.Compiler.CompilerParameters
            $CompilerParameters.CompilerOptions = "/unsafe"

            # Needs to be unsafe so that we can reference the address for the Bytes variable
            # and create and IntPtr from it that is used by the stream to track where in the
            # input stream the reader currently is
            Add-Type -CompilerParameters $CompilerParameters -TypeDefinition @"
using System.Runtime.InteropServices.ComTypes;
using System.IO;
using System;
 
namespace BAMCIS.FileIO.ISO
{
    public class ISOFile
    {
        private ISOFile()
        {
        }
 
        public unsafe static void Create(string path, object stream, int blockSize, int totalBlocks)
        {
            int Bytes = 0;
            IntPtr SeekPointer = (IntPtr)(&Bytes);
            byte[] Buffer = new byte[blockSize];
            IStream InputStream = stream as IStream;
 
            using (FileStream FStream = System.IO.File.OpenWrite(path))
            {
                if (FStream != null)
                {
                    while (totalBlocks > 0)
                    {
                        InputStream.Read(Buffer, blockSize, SeekPointer);
                        FStream.Write(Buffer, 0, Bytes);
                        totalBlocks += -1;
                    }
                }
                else
                {
                    throw new InvalidOperationException(String.Format("The file stream at {0} was null.", path));
                }
            }
        }
    }
}
"@

        }

        [BAMCIS.FileIO.ISO.IMAPI_MEDIA_PHYSICAL_TYPE]$MediaType = [System.Enum]::Parse([BAMCIS.FileIO.ISO.IMAPI_MEDIA_PHYSICAL_TYPE], $Media)
       
        Write-Verbose -Message "Selected media type is $($MediaType.ToString()) with value $([System.Int32]$MediaType)."

        $Image = New-Object -ComObject IMAPI2FS.MsftFileSystemImage -Property @{VolumeName = $Title}
        $Image.ChooseImageDefaultsForMediaType(([Int32]$MediaType)) 
    }

    Process {
        foreach ($Item in $Content)
        {
            if ($Item -isnot [System.IO.FileInfo] -and $Item -isnot [System.IO.DirectoryInfo])
            {
                $Item = Get-Item -LiteralPath $Item
            }

            Write-Verbose -Message "Adding $($Item.FullName) to image."

            try 
            { 
                $Image.Root.AddTree($Item.FullName, $true) 
            } 
            catch [Exception] 
            { 
                throw "$($_.Exception.Message) : Try a different media type." 
            } 
        }
    }

    End {
        if ($BootOptions -ne $null) 
        { 
            $Image.BootImageOptions = $BootOptions 
        }  
    
        $Result = $Image.CreateResultImage()  

        if (-not ($Target = New-Item -Path $Destination -ItemType File -Force:$Force -ErrorAction SilentlyContinue))
        {
            throw "Could not create file at $Destination. Use -Force parameter to overwrite an existing file."
        }

        [BAMCIS.FileIO.ISO.ISOFile]::Create(
            $Target.FullName,
            $Result.ImageStream,
            $Result.BlockSize,
            $Result.TotalBlocks
        ) 
    
        Write-Verbose -Message "Target image $($Target.FullName) has been created"
    
        Write-Output -InputObject $Target
    }
}