BAMCIS.Common.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
#region Test Functions

Function Get-RegistryKeyEntries {
    <#
  .SYNOPSIS
   Gets all of the properties and their values associated with a registry key.
 
  .DESCRIPTION
   The Get-RegistryKeyEntries cmdlet gets each entry and its value for a specified registry key.
 
  .PARAMETER Path
   The registry key path in the format that PowerShell can process, such as HKLM:\Software\Microsoft or Registry::HKEY_LOCAL_MACHINE\Software\Microsoft
 
  .INPUTS
   System.String
 
    You can pipe a registry path to Get-RegistryKeyEntries.
 
  .OUTPUTS
   System.Management.Automation.PSCustomObject[]
 
  .EXAMPLE
   Get-RegistryEntries -Path HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall
 
   Gets all of the entries associated with the registry key. It does not get any information about subkeys.
 
  .NOTES
   AUTHOR: Michael Haken    
   LAST UPDATE: 2/27/2016
 
  .FUNCTIONALITY
   The intended use of this cmdlet is to supplement the Get-ItemProperty cmdlet to get the values for every entry in a registry key.
 #>

    [CmdletBinding()]
    [OutputType([System.Management.Automation.PSCustomObject[]])]
    Param(
        [Parameter(Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Mandatory = $true)]
        [ValidateScript({
            Test-Path -Path $_
        })]
        [ValidateNotNullOrEmpty()]
        [System.String]$Path
    )

    Begin {}

    Process
    {
        Get-Item -Path $Path | Select-Object -ExpandProperty Property | ForEach-Object {
            Write-Output -InputObject ([PSCustomObject]@{"Path"=$Path;"Property"="$_";"Value"=(Get-ItemProperty -Path $Path -Name $_ | Select-Object -ExpandProperty $_)})
        }
    }

    End {}
}

Function Invoke-WhereNotMatchIn {
    <#
  .SYNOPSIS
   The cmdlet identifies items from an input that do not match a set of match terms. Essentially, this filters out items from the
   input against an array of filters.
 
  .DESCRIPTION
   The cmdlet takes an input array of objects. It compares each of these objects, or a property of the object against
   an array of match terms. If the item (or its property) does not match any of the match terms, it is returned to the pipeline.
 
  .PARAMETER InputObject
   An array of items that need to be filtered. The items can be primitive types, strings, or objects. If the items are complex objects, you should
   specify a property to be compared against the match terms.
 
  .PARAMETER Matches
   The set of string values to compare against the input items or a property of the input items. Any item in the Matches parameter that satifies
   the "-ilike" operator against the input item will cause that item to be filtered out of the results.
 
  .PARAMETER Property
   If the input items are complex objects, specify a property of those items to be compared against the Matches parameter.
 
  .EXAMPLE
   $Items = @("one", "oneTwo", "two", "oneThree", "three")
   $Results = Invoke-WhereNotMatchIn -Input $Items -Matches @("one*", "*two*")
 
   The results of this operation would be an array as follows: @("two", "three").
 
  .EXAMPLE
   $Items = @([PSCustomObject]@{Name = "One"; Value = "1"}, @{Name = "Two"; Value = "2"})
   $Results = Invoke-WhereNotMatchIn -Input $Items -Matches ("one") -Property "Name"
    
  .INPUTS
   System.Object[]
 
  .OUTPUTS
   System.Object[]
 
  .NOTES
   AUTHOR: Michael Haken
   LAST UPDATED: 10/24/2017
 
 #>

    [CmdletBinding()]
    [Alias("Where-NotMatchIn")]
    [OutputType([System.Object[]])]
    Param(
        [Parameter(Position = 0, ValueFromPipeline = $true)]
        [System.Object[]]$InputObject,

        [Parameter(Position = 1)]
        [System.String[]]$Matches,

        [Parameter()]
        [System.String]$Property = [System.String]::Empty
    )

    Begin {
    }

    Process {
        

        foreach($Item in $InputObject) {
            $Match = $false

            if ($Property -eq [System.String]::Empty) {
                $Value = $Item
            }
            else {
                $Value = $Item.$Property
            }

            foreach ($Matcher in $Matches) {
                
                if ($Value -ilike $Matcher) {
                    $Match = $true
                    break
                }
            }

            if (!$Match) {
                Write-Output -InputObject $Item
            }
        }
    }

    End {       
    }
}

Function Test-RegistryKeyProperty {
    <#
  .SYNOPSIS
   Tests the existence of a registry value
 
  .DESCRIPTION
   The Test-RegistryKeyProperty cmdlet test the extistence of a registry value (property of a key).
 
  .PARAMETER Key
   The registry key to test for containing the property.
 
  .PARAMETER PropertyName
   The property name to test for.
 
        .EXAMPLE
   Test-RegistryKeyProperty -Key "HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Component Based Servicing" -PropertyName PendingFileRenameOperations
          
   Returns true or false depending on the existence of the property
 
  .INPUTS
   None
 
  .OUTPUTS
   System.Boolean
 
  .NOTES
   AUTHOR: Michael Haken
   LAST UPDATE: 2/28/2016
 #>

    [CmdletBinding()]
    [OutputType([System.Boolean])]
    Param (
        [Parameter(Position = 0, Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [System.String]$Key,

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

    Begin {
    }

    Process {
        Get-ItemProperty -Path $Key -Name $PropertyName -ErrorAction SilentlyContinue | Out-Null
        Write-Output -InputObject $?
    }

    End {
    }
}

Function Test-IsLocalAdmin {
    <#
  .SYNOPSIS
   Tests if the current user has local administrator privileges.
 
  .DESCRIPTION
   The Test-IsLocalAdmin cmdlet tests the user's current Windows Identity for inclusion in the BUILTIN\Administrators role.
 
  .INPUTS
   None
 
  .OUTPUTS
   System.Boolean
 
  .EXAMPLE
   Test-IsLocalAdmin
 
   This command returns true if the current user is running the session with local admin credentials and false if not.
 
  .NOTES
   AUTHOR: Michael Haken    
   LAST UPDATE: 2/27/2016
 
  .FUNCTIONALITY
   The intended use of this cmdlet is to test for administrative credentials before running other commands that require them.
 #>

    [CmdletBinding()]
    [OutputType([System.Boolean])]
    Param()

    Begin {}

    Process {
        Write-Output -InputObject ([System.Security.Principal.WindowsPrincipal][System.Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
    }

    End {}
 }

#endregion



#region Parallel / Using / Processing

Function Invoke-ForEachParallel {
    <#
  .SYNOPSIS
   Runs a script in a multi-threaded foreach.
 
  .DESCRIPTION
   The cmdlet runs through each input value and executes the script in a new thread.
 
  .PARAMETER ScriptBlock
   The script to execute on each input object.
 
  .PARAMETER InputObject
   The array of items to provide as input to the foreach.
 
  .PARAMETER Parameters
   A hashtable of additional parameters to provide to the script. For example @{Name = "MyService", Priority = 1} could be used by a scriptblock that looked like
 
   {
    Param(
     $Name,
     $Priority
    )
 
    Write-Host $Name
    Write-Host $Priority
   }
 
  .PARAMETER InputParamName
   If the input object needs to be associated with a parameter in the script, define its parameter name with this parameter. For example, consider the following Windows services:
 
   @("Winmgmt", "WinRM") | Invoke-ForEachParallel {
    Param(
     $Type
     $Name
    )
    Get-Service $Name
   } -InputParamName "Name"
 
   This will ensure that Winmgmt and WinRM are provided to the $Name parameter and not $Type
 
  .PARAMETER MinimumThreads
   The minimum number of threads to use, this defaults to 1.
 
  .PARAMETER MaximumThreads
   The maximum number of threads to use, this defaults to 4. This must be greater than or equal to the minimum threads.
 
  .PARAMETER WaitTime
   The amount of time, in milliseconds, the function waits in between checking the status of each task. For long running tasks
   you can increase this time to utilize less resources during execution.
 
        .EXAMPLE
   @("Winmgmt", "WinRM") | Invoke-ForEachParallel {
    Param(
     $Name
    )
    Get-Service $Name
   }
 
   This will return the service objects for the Winmgmt and WinRM services.
 
  .EXAMPLE
   $Results = Invoke-ForEachParallel -InputObject ("Hello", "Goodbye") -ScriptBlock {
    Param(
     $Greeting,
     $FirstName,
     $LastName
    )
 
    Write-Output -InputObject ($Greeting $FirstName $LastName)
 
   } -Parameters @{FirstName = "John", LastName = "Smith"}
 
   The example would execute two tasks, one outputing "Hello John Smith" and the other outputing "Goodbye John Smith", but not
   necessarily in that order. The InputObject items are mapped against the parameter in the first position of the script, $Greeting,
   while the additional parameters are mapped by matching their name.
 
  .INPUTS
   System.Object[]
 
  .OUTPUTS
   System.Object[]
 
  .NOTES
   AUTHOR: Michael Haken
   LAST UPDATE: 10/26/2016
 #>

    [CmdletBinding()]
    [OutputType([System.Object[]])]
    [Alias("ForEach-ObjectParallel")]
    Param(           
        [Parameter(Mandatory = $true, Position = 0, ParameterSetName = "ScriptBlock")]
        [ValidateNotNull()]
        [System.Management.Automation.ScriptBlock]$ScriptBlock,

        [Parameter(Mandatory = $true, Position = 0, ParameterSetName = "Cmdlet")]
        [ValidateScript({
            Get-Command -Name $_
        })]
        [System.String]$Cmdlet,

        [Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 1)]
        [ValidateNotNull()]
        [System.Object[]]$InputObject,

        [Parameter()]
        [ValidateNotNull()]
        [System.Collections.Hashtable]$Parameters,

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [System.String]$InputParamName = [System.String]::Empty,

        [Parameter()]
        [System.UInt32]$MinimumThreads = 1,

        [Parameter()]
        [ValidateScript({
            $_ -ge $MinimumThreads
        })]
        [System.UInt32]$MaximumThreads = 4,

        [Parameter()]
        [System.UInt32]$WaitTime = 100
    )

    Begin {
    }

    Process {
        $Jobs = New-Object -TypeName System.Collections.ArrayList
        $SessionState = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault2()
        $RunspacePool = [System.Management.Automation.Runspaces.RunspaceFactory]::CreateRunspacePool($MinimumThreads, $MaximumThreads, $SessionState, $Host)
        $RunspacePool.Open()

        foreach ($Item in $InputObject) {
            $Pipeline = [System.Management.Automation.PowerShell]::Create()

            if ($PSCmdlet.ParameterSetName -eq "ScriptBlock")
            {
                $Pipeline.AddScript($ScriptBlock) | Out-Null
            }
            elseif ($PSCmdlet.ParameterSetName -eq "Cmdlet")
            {
                $Pipeline.AddCommand($Cmdlet) | Out-Null
            }
            else
            {
                throw (New-Object -TypeName System.ArgumentException("The parameter set name could not be determined from the given parameters."))
            }

            if ($Parameters.Length -gt 0)
            {
                $Pipeline.AddParameters($Parameters) | Out-Null
            }

            if (![System.String]::IsNullOrEmpty($InputParamName))
            {
                $Pipeline.AddParameter($InputParamName, $Item) | Out-Null
            }
            else
            {
                $Pipeline.AddArgument($Item) | Out-Null
            }

            $Pipeline.RunspacePool = $RunspacePool
            $AsyncHandle = $Pipeline.BeginInvoke()

            $Jobs.Add(@{Handle = $AsyncHandle; Pipeline = $Pipeline}) | Out-Null
        }

        $Results = @()
        $TotalJobs = $Jobs.Count

        while ($Jobs.Count -gt 0)
        {
            Write-Progress -Activity "Waiting for async tasks" `
                        -PercentComplete ((($TotalJobs - $Jobs.Count) / $TotalJobs) * 100) `
                        -Status ( ($TotalJobs - $Jobs.Count).ToString() + " of $TotalJobs completed, $($Jobs.Count) remaining")

            foreach($Job in ($Jobs | Where-Object {$_.Handle.IsCompleted -eq $true}))
            {
                $Results += $Job.Pipeline.EndInvoke($Job.Handle)
                $Job.Pipeline.Dispose() | Out-Null
                $Jobs.Remove($Job)
            }

            Start-Sleep -Milliseconds $WaitTime
        }

        Write-Progress -Activity "Waiting for async tasks" -Completed

        $RunspacePool.Close() | Out-Null
        $RunspacePool.Dispose() | Out-Null

        Write-Output -InputObject $Results
    }

    End {
    }
}

Function Invoke-CommandInNewRunspace {
    <#
  .SYNOPSIS
   Runs a scriptblock in a new powershell runspace.
 
  .DESCRIPTION
   The Invoke-CommandInNewRunspace cmdlet uses a clean PowerShell runspace to execute the provided script block.
 
  .PARAMETER ScriptBlock
   The script to execute on each input object.
 
  .PARAMETER Parameters
   A hashtable of additional parameters to provide to the script. For example @{Name = "MyService", Priority = 1} could be used by a scriptblock that looked like
 
   {
    Param(
     $Name,
     $Priority
    )
 
    Write-Host $Name
    Write-Host $Priority
   }
 
        .EXAMPLE
   Invoke-CommandInNewRunspace -ScriptBlock {Get-Service}
          
   Invokes the Get-Service cmdlet in a new runspace.
 
  .EXAMPLE
   Invoke-CommandInNewRunspace -ScriptBlock {
    Param(
     $Name
    )    
    
    Get-Process $Name
   } -Parameters @{Name = "winlogon"}
 
   Performs a Get-Process for the winlogon process in a new runspace
 
  .INPUTS
   None
 
  .OUTPUTS
   System.Object
 
   This depends on what is returned from the ScriptBlock
 
  .NOTES
   AUTHOR: Michael Haken
   LAST UPDATE: 10/26/2016
 #>

    [CmdletBinding()]
    [OutputType([System.Object])]
    Param(
        
        [Parameter(Mandatory = $true, Position = 0, ParameterSetName = "ScriptBlock")]
        [ValidateNotNull()]
        [System.Management.Automation.ScriptBlock]$ScriptBlock,

        [Parameter(Mandatory = $true, Position = 0, ParameterSetName = "Cmdlet")]
        [ValidateScript({
            Get-Command -Name $_
        })]
        [System.String]$Cmdlet,

        [Parameter(Position = 1)]
        [ValidateNotNull()]
        [System.Collections.Hashtable]$Parameters
    )

    Begin {
    }

    Process {
        $Results = $null
        $Runspace = [System.Management.Automation.Runspaces.RunspaceFactory]::CreateRunspace()

        #Create a new PowerShell instance
        $Pipeline = [System.Management.Automation.PowerShell]::Create()

        try {
            #Assign the PowerShell instance to the new RunspacePool we created
            $Pipeline.Runspace = $Runspace

            #Open the runspace
            $Runspace.Open()

            #If the cmdlet was run using a script block, add it
            if ($PSCmdlet.ParameterSetName -eq "ScriptBlock")
            {
                $Pipeline.AddScript($ScriptBlock) | Out-Null
            }
            elseif ($PSCmdlet.ParameterSetName -eq "Cmdlet")
            {
                $Pipeline.AddCommand($Cmdlet) | Out-Null
            }
            else
            {
                throw New-Object -TypeName System.ArgumentException("The parameter set name could not be determined from the given parameters.")
            }

            #Add parameters if they are defined
            if ($Parameters.Length -gt 0)
            {
                $Pipeline.AddParameters($Parameters) | Out-Null
            }

            #Invoke the command synchronously
            $Results = $Pipeline.Invoke()
        }
        finally {
            #Dispose the powershell instance
            $Pipeline.Dispose() | Out-Null
        
            #Terminate the runspace
            $Runspace.Close() | Out-Null
            $Runspace.Dispose() | Out-Null
        }

        Write-Output -InputObject $Results
    }

    End {
        
    }
}

Function Start-ProcessWait {
    <#
  .SYNOPSIS
   Starts a new process and waits for it to complete.
 
  .DESCRIPTION
   This cmdlet starts a new process using .NET System.Diagnostics.Process and waits for it to complete. It optionally writes the standard out of the process to the log file.
 
  .PARAMETER FilePath
   The path to the executable, script, msi, msu, etc to be executed.
 
  .PARAMETER ArgumentList
   An array of arguments to run with the file being executed. This defaults to an empty array.
 
  .PARAMTER EnableLogging
   Specify to write standard output or standard errors to the log file.
 
  .INPUTS
   None
 
  .OUTPUTS
   None
 
        .EXAMPLE
   Start-ProcessWait -FilePath "c:\installer.msi" -EnableLogging -ArgumentList @("/qn")
 
   Launches a quiet installation from installer.msi with a no restart option. Logging is also enabled.
 
  .NOTES
   AUTHOR: Michael Haken
   LAST UPDATE: 8/24/2016
 #>

    [CmdletBinding()]
    [OutputType()]
    Param(
        [Parameter(Mandatory=$true)]
        [ValidateScript({
            Test-Path -Path $_    
        })]
        [System.String]$FilePath,

        [Parameter()]
        [ValidateNotNull()]
        [System.String[]]$ArgumentList = @(),

        [Parameter()]
        [Switch]$EnableLogging
    )

    Begin {
    }

    Process {
        if (Test-Path -Path $FilePath) {
            [System.IO.FileInfo]$FileInfo = New-Object -TypeName System.IO.FileInfo($FilePath)

            [System.Diagnostics.Process]$Process = New-Object -TypeName System.Diagnostics.Process
            $Process.StartInfo.RedirectStandardOutput = $true
            $Process.StartInfo.UseShellExecute = $false
            $Process.StartInfo.CreateNoWindow = $true
            $Process.StartInfo.RedirectStandardError = $true

            switch($FileInfo.Extension.ToUpper()) {
                ".MSU" {
                    $ArgumentList += "$FilePath"
                    $Process.StartInfo.Filename = "$env:SystemRoot\System32\WUSA.EXE"
                    $Process.StartInfo.Arguments = ($ArgumentList -join " ")
                    break
                }
                ".MSP" {
                    $ArgumentList += "$FilePath"
                    $ArgumentList += "/update"
                    $Process.StartInfo.Filename = "MSIEXEC.EXE"
                    $Process.StartInfo.Arguments = ($ArgumentList -join " ")
                    break
                }
                ".MSI" {
                    $ArgumentList += "$FilePath"
                    $Process.StartInfo.Filename = "MSIEXEC.EXE"
                    $Process.StartInfo.Arguments = ($ArgumentList -join " ")
                    break
                }
                default {
                    $Process.StartInfo.Filename = "$FilePath"
                    $Process.StartInfo.Arguments = ($ArgumentList -join " ")
                    break
                }
            }

            Write-Log -Message "Executing $FilePath $($ArgumentList -Join " ")" -Level VERBOSE

            $Process.Start() | Out-Null
            
            if ($EnableLogging) {
                while (!$Process.HasExited) {
                     while (![System.String]::IsNullOrEmpty(($Line = $Process.StandardOutput.ReadLine()))) {
                        Write-Log -Message $Line -NoInfo
                    }

                    Start-Sleep -Milliseconds 100
                }

                if ($Process.ExitCode -ne 0) {
                    $Line = $Process.StandardError.ReadToEnd()
                    if (![System.String]::IsNullOrEmpty($Line)) {
                        Write-Log -Message $Line -Level ERROR -NoInfo
                    }
                }
                else {
                    $Line = $Process.StandardOutput.ReadToEnd()
                    if (![System.String]::IsNullOrEmpty($Line)) {
                        Write-Log -Message $Line -NoInfo
                    }
                }
            }
            else {
                $Process.WaitForExit()
            }
        }
        else {
            Write-Log -Message "$FilePath not found." -Level WARNING
        }
    }

    End {}
}

Function Invoke-Using {
    <#
        .SYNOPSIS
            Provides a C#-like using() block to automatically handle disposing IDisposable objects.
 
        .DESCRIPTION
            The cmdlet takes an InputObject that should be an IDisposable, executes the ScriptBlock, then disposes the object.
 
        .PARAMETER InputObject
            The object that needs to be disposed of after running the scriptblock.
 
        .PARAMETER ScriptBlock
            The scriptblock to execute with the "using" variable.
 
        .EXAMPLE
            Invoke-Using ([System.IO.StreamWriter]$Writer = New-Object -TypeName System.IO.StreamWriter([System.Console]::OpenStandardOutput())) {
                $Writer.AutoFlush = $true
                [System.Console]::SetOut($Writer)
                $Writer.Write("This is a test.")
            }
 
            The StreamWriter is automatically disposed of after the script block is executed. Future calls to $Writer would fail. Please notice
            that the open "{" bracket needs to be on the same line as the cmdlet.
 
        .INPUTS
            System.Management.Automation.ScriptBlock
 
        .OUTPUTS
            None
 
        .NOTES
            AUTHOR: Michael Haken
   LAST UPDATE: 6/21/2017
 
    #>

    [Alias("Using")]
    [CmdletBinding()]
    [OutputType()]
    Param(
        [Parameter(Mandatory = $true)]
        [ValidateNotNull()]
        [ValidateScript({
            $_ -is [System.IDisposable]
        })]
        [System.Object]$InputObject,
 
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [ValidateNotNull()]
        [System.Management.Automation.ScriptBlock]$ScriptBlock
    )
    
    Begin {
    }
    
    Process 
    {       
        try
        {
            & $ScriptBlock
        }
        finally
        {
            if ($InputObject -ne $null)
            {
                $InputObject.Dispose()
            }
        }
    }

    End {
    }
}

#endregion



#region Converters

Function ConvertFrom-Xml {
    <#
  .SYNOPSIS
   Converts an Xml object to a PSObject.
 
  .DESCRIPTION
   The ConvertFrom-Xml recursively goes through an Xml object and enumerates the properties of each inputted element. Those properties are accessed and added to the returned object.
 
   An XmlElement that has attributes and XmlText will end up with the XmlText value represented as a "#name" property in the resulting object.
 
  .EXAMPLE
   ConvertFrom-Xml -InputObject $XmlObj
 
   Returns an PSObject constructed from the $XmlObj variable
 
  .PARAMETER InputObject
   The InputObject is an Xml type in the System.Xml namespace. It could be an XmlDocument, XmlElement, or XmlNode for example. It cannot be a collection of Xml objects.
 
  .INPUTS
   System.Xml
 
  .OUTPUTS
   System.Management.Automation.PSObject
 
  .NOTES
   AUTHOR: Michael Haken
   LAST UPDATE: 3/31/2015
 #>

    [CmdletBinding()]
    [OutputType([System.Management.Automation.PSObject])]
    Param(
        [Parameter(Position = 0, ValueFromPipeline = $true, Mandatory = $true)]
        [ValidateScript({
            $_.GetType().Namespace -eq "System.Xml"
        })]
        $InputObject
    )

    Begin {       
    }

    Process {
        $private:Hash = @{}
        
        Get-Member -InputObject $InputObject -MemberType Property | Where-Object {$_.Name -ne "xml" -and (![System.String]::IsNullOrEmpty($_.Name))} | ForEach-Object {
            $PropertyName = $_.Name
            $InputItem = $InputObject.($PropertyName)

            #There are multiple items with the same tag name
            if ($InputItem.GetType() -eq [System.Object[]]) {
                
                #Make the tag name an array
                $private:Hash.($PropertyName) = @()

                #Go through each item in the array
                $InputItem | Where-Object {$_ -ne $null} | ForEach-Object {
                    
                    #Item is an object in the array
                    $Item = $_
                    [System.Type]$Type = $Item.GetType()

                    if ($Type.IsPrimitive -or $Type -eq [System.String]) {                   
                        $private:Hash.($PropertyName) = $Item
                    }
                    else {
                        #Create a temp variable to hold the new object that will be added to the array
                        $Temp = @{}  
                                
                        #Make attributes properties of the object
                        $Item.Attributes | ForEach-Object {
                            $Temp.($_.Name) = $_.Value
                        }

                        #As an XmlElement, the element will have at least 1 childnode, it's value
                        $Item.ChildNodes | Where-Object {$_ -ne $null -and ![System.String]::IsNullOrEmpty($_.Name)} | ForEach-Object {
                            $ChildNode = $_
   
                            if ($ChildNode.HasChildNodes) {
                                #If the item has 1 childnode and the childnode is XmlText, then the child is this type of element,
                                #<Name>ValueText</Name>, so its child is just the value
                                if ($ChildNode.ChildNodes.Count -eq 1 -and $ChildNode.ChildNodes[0].GetType() -eq [System.Xml.XmlText] -and !($ChildNode.HasAttributes)) {
                                    $Temp.($ChildNode.ToString()) = $ChildNode.ChildNodes[0].Value
                                }
                                else {
                                    $Temp.($ChildNode.ToString()) = ConvertFrom-Xml -InputObject $ChildNode
                                }
                            }
                            else {
                                $Temp.($ChildNode.ToString()) = $ChildNode.Value
                            }
                        }
                    
                        $private:Hash.($PropertyName) += $Temp
                    }
                }
            }
            else {
                if ($InputItem -ne $null) {
                    $Item = $InputItem
                    [System.Type]$Type = $InputItem.GetType()
                    
                    if ($Type.IsPrimitive -or $Type -eq [System.String]) {                   
                        $private:Hash.($PropertyName) = $Item
                    }
                    else {

                        $private:Hash.($PropertyName) = @{}  
                                
                        $Item.Attributes | ForEach-Object {
                            $private:Hash.($PropertyName).($_.Name) = $_.Value
                        }

                        $Item.ChildNodes | Where-Object {$_ -ne $null -and ![System.String]::IsNullOrEmpty($_.Name)} | ForEach-Object {
                            $ChildNode = $_
                            
                            if ($ChildNode.HasChildNodes) {
                                if ($ChildNode.ChildNodes.Count -eq 1 -and $ChildNode.ChildNodes[0].GetType() -eq [System.Xml.XmlText] -and !($ChildNode.HasAttributes)) {      
                                    $private:Hash.($PropertyName).($ChildNode.ToString()) = $ChildNode.ChildNodes[0].Value
                                }
                                else {
                                    $private:Hash.($PropertyName).($ChildNode.ToString()) = ConvertFrom-Xml -InputObject $ChildNode
                                }
                            }
                            else {
                                $private:Hash.($PropertyName).($ChildNode.ToString()) = $ChildNode.Value
                            }
                        }
                    }
                }
            }                  
        }

         Write-Output -InputObject (New-Object -TypeName System.Management.Automation.PSObject -Property $private:Hash)
    }

    End {      
    }
}

Function ConvertTo-HtmlTable {
    <#
  .SYNOPSIS
   Converts an object to an HTML table.
 
  .DESCRIPTION
   The ConvertTo-HtmlTable cmdlet takes an input object and converts it to an HTML document containing a table. The html
   document is either written out to stdout or written to file if a destination is specified.
 
  .EXAMPLE
   ConvertTo-HtmlTable -CsvPath c:\test.csv -Title "Test Import File" -Destination c:\test.html
 
   Converts the csv file to an html file and saves the html to the specified destination.
 
  .PARAMETER CsvPath
   The path to the CSV file that will be converted to HTML. Currently, this is the only supported input format.
 
  .PARAMETER Title
   An optional title to display on the HTML.
 
  .PARAMETER Destination
   An optional parameter to save the HTML content to a file. If this parameter is not specified or is Null or Empty, the HTML will be written to the pipeline.
 
  .PARAMETER IgnoreHeaders
   An array of any headers in the CSV file to ignore when creating the HTML table. Data in these columns will not be added to the table.
 
  .INPUTS
   None
 
  .OUTPUTS
   System.String
 
  .NOTES
   AUTHOR: Michael Haken
   LAST UPDATE: 1/15/2017
 #>

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

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [System.String]$Title = [System.String]::Empty,

        [Parameter(Position = 1)]
        [ValidateNotNullOrEmpty()]
        [System.String]$Destination = [System.String]::Empty,

        [Parameter(ParameterSetName="Csv")]
        [ValidateNotNull()]
        [System.String[]]$IgnoreHeaders = @()
    )

    Begin {
    }

    Process {
        switch ($PSCmdlet.ParameterSetName) {
            "Csv" {
                $Data = Import-Csv -Path $CsvPath
                if ($Data.Count -gt 0) {
                    $Headers = Get-Member -InputObject $Data[0] -MemberType NoteProperty | Select-Object -ExpandProperty Name | Where-Object {$_.ToString().ToLower() -notin $IgnoreHeaders.ToLower()}
                }
                else {
                    $Headers = @()
                    Write-Log -Message "No content in the CSV." -Level VERBOSE
                }
            }
            default {
                throw "Could not determine parameter set."
            }
        }

        $Html = @"
<!DOCTYPE html>
<html>
 <head>
  <meta name="viewport" content="width=device-width" />
  <title>$Title</title>
 </head>
    <style>
        .logtable {
            width:100%;
            table-layout:fixed;
            border:1px solid black;
        }
         
        .logtable td {
            word-break:break-all;
            word-wrap:break-word;
            vertical-align:top;
   text-align:left;
        }
 
        .logtable th {
            text-align:center;
        }
    </style>
 <body style=`"width:1200px;margin-left:auto;margin-right:auto;`">
        <H1 style=`"text-align:center;`">$Title</H1>
        <div>
    <table class=`"logtable`">
    <thead>
 
"@


        foreach ($Header in $Headers) {
            $Html += "<th>$Header</th>"
        }

        $Html += "</thead><tbody>"

        foreach ($Obj in $Data) {
            $Html += "<tr>"

            $Props = Get-Member -InputObject $Obj -MemberType NoteProperty | Select-Object -ExpandProperty Name | Where-Object {$_.ToString().ToLower() -notin $IgnoreHeaders.ToLower()}

            foreach ($Prop in $Props) {
                $Html += "<td>" + $Obj.$Prop + "</td>"
            }

            $Html += "</tr>"
        }

        $Html += "</tbody></table></div></body></html>"

        if (![System.String]::IsNullOrEmpty($Destination)) {
            Set-Content -Path $Destination -Value $Html -Force
        }
        else {
            Write-Output -InputObject $Html
        }
    }

    End {
    }
}

Function Merge-Hashtables {
    <#
  .SYNOPSIS
   Merges two hashtables.
 
  .DESCRIPTION
   The cmdlet merges a second hashtable with a source one. The second hashtable will add or overwrite its values to a copy of the first. Neither of the two input hashtables are modified.
 
  .PARAMETER Source
   The source hashtable that will be added to or overwritten. The original hashtable is not modified.
 
  .PARAMETER Update
   The hashtable that will be merged into the source. This hashtable is not modified.
 
  .EXAMPLE
   Merge-Hashtables -Source @{"Key" = "Test"} -Data @{"Key" = "Test2"; "Key2" = "Test3"}
 
   This cmdlet results in a hashtable that looks like as follows: @{"Key" = "Test2"; "Key2" = "Test3"}
 
  .INPUTS
            None
 
        .OUTPUTS
            System.Collections.Hashtable
 
        .NOTES
            AUTHOR: Michael Haken
   LAST UPDATE: 8/21/2017    
 #>


    [CmdletBinding()]
    [OutputType([System.Collections.Hashtable])]
    Param(
        [Parameter(Mandatory = $true)]
        [ValidateNotNull()]
        [System.Collections.Hashtable]$Source,

        [Parameter(Mandatory = $true)]
        [ValidateNotNull()]
        [System.Collections.Hashtable]$Update
    )

    Begin {
    }

    Process {
        # Make a copy of the source so it is not modified
        [System.Collections.Hashtable]$Output = $Source.Clone()

        # Check each key in the update to see if the output already has it
        foreach ($Key in $Update.Keys)
        {
            # If it does, update the value
            if ($Output.ContainsKey($Key))
            {
                $Output[$Key] = $Update[$Key]
            }
            else 
            {
                # If not, add the key/value
                $Output.Add($Key, $Update[$Key])
            }
        }

        Write-Output -InputObject $Output
    }

    End {
    }
}

Function ConvertTo-Hashtable {
    <#
  .SYNOPSIS
   Converts a PSCustomObject to a Hashtable.
 
  .DESCRIPTION
   The cmdlet takes a PSCustomObject and converts all of its property key/values to a Hashtable. You can specify keys from the PSCustomObject to exclude or specify that empty values not be added to the Hashtable.
 
  .PARAMETER InputObject
   The PSCustomObject to convert.
 
  .PARAMETER Exclude
   The key values from the PSCustomObject not to include in the Hashtable.
 
  .PARAMETER NoEmpty
   Specify to not include keys with empty or null values from the PSCustomObject in the Hashtable.
 
  .EXAMPLE
   ConvertTo-Hashtable -InputObject ([PSCustomObject]@{"Name" = "Smith"})
 
   Converts the inputted PSCustomObject to a hashtable.
 
  .EXAMPLE
   ConvertTo-Hashtable -InputObject ([PSCustomObject]@{"LastName" = "Smith", "Middle" = "", "FirstName" = "John"}) -NoEmpty -Exclude @("FirstName")
 
   Converts the inputted PSCustomObject to a hashtable. The empty property, Middle is excluded, and the property FirstName is excluded explicitly. This results
   in a hashtable @{"LastName" = "Smith"}
 
  .INPUTS
            System.Management.Automation.PSCustomObject
 
        .OUTPUTS
            System.Collections.Hashtable
 
        .NOTES
            AUTHOR: Michael Haken
   LAST UPDATE: 8/21/2017    
 #>

    [CmdletBinding()]
    [OutputType([System.Collections.Hashtable])]
    Param(
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [ValidateNotNull()]
        [PSCustomObject]$InputObject,

        [Parameter()]
        [ValidateNotNull()]
        [System.String[]]$Exclude = @(),

        [Parameter()]
        [Switch]$NoEmpty
    )

    Begin {
    }
    
    Process {
        [System.Collections.Hashtable]$Result = @{}

        $InputObject | Get-Member -MemberType "*Property" | Select-Object -ExpandProperty Name | ForEach-Object {
            if ($Exclude -inotcontains $_) {
                if ($NoEmpty -and -not ($InputObject.$_ -eq $null -or $InputObject.$_ -eq ""))
                {
                    Write-Log -Message "Property $_ has an empty/null value." -Level VERBOSE
                }
                else 
                {
                    $Result.Add($_, $InputObject.$_)
                }
            }
            else {
                Write-Log -Message "Property $_ excluded." -Level VERBOSE
            }
        }

        Write-Output -InputObject $Result
    }

    End {
    }
}

Function Convert-SecureStringToString {
    <#
  .SYNOPSIS
   The cmdlet converts a secure string to standard string.
 
  .DESCRIPTION
   The cmdlet converts a secure string to standard string.
 
  .PARAMETER SecureString
   The secure string to convert to a standard string
 
        .PARAMETER Encoding
             Defines the encoding that is used to produce the output string. This defaults to Unicode.
 
  .INPUTS
   System.Security.SecureString
   
  .OUTPUTS
   System.String
 
  .EXAMPLE
   Convert-SecureStringToString -SecureString (ConvertTo-SecureString -String "test" -AsPlainText -Force)
 
   Converts the secure string created from the text "test" back to plain text.
 
  .NOTES
   AUTHOR: Michael Haken
   LAST UPDATE: 1/25/2018
 #>

    [CmdletBinding()]
    [OutputType([System.String])]
    Param(
        [Parameter(Position = 0, ValueFromPipeline = $true, Mandatory = $true)]
        [System.Security.SecureString]$SecureString,

        [Parameter()]
        [ValidateNotNull()]
        [System.Text.Encoding]$Encoding = [System.Text.Encoding]::Unicode
    )

    Begin {}

    Process { 
        [System.String]$PlainText = [System.String]::Empty
        [System.IntPtr]$IntPtr = [System.IntPtr]::Zero

        try 
        {     
            $IntPtr = [System.Runtime.InteropServices.Marshal]::SecureStringToGlobalAllocUnicode($SecureString)     
            $PlainText = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($IntPtr)  
            [System.Byte[]]$Bytes = [System.Text.Encoding]::Unicode.GetBytes($PlainText)

            $PlainText = $Encoding.GetString($Bytes)

            Write-Output -InputObject $PlainText
        }   
        finally 
        {     
            if ($IntPtr -ne $null -and $IntPtr -ne [System.IntPtr]::Zero) 
            {       
                [System.Runtime.InteropServices.Marshal]::ZeroFreeGlobalAllocUnicode($IntPtr)     
            }   
        }
    }

    End {      
    }
}

Function ConvertFrom-UnixTimestamp {
    <#
  .SYNOPSIS
   Converts a Unix timestamp to a DateTime object.
   
  .DESCRIPTION
   The cmdlet converts a unix timestamp to a DateTime object. The timestamp can be in milliseconds or seconds.
   
  .PARAMETER Timestamp
   The unix timestamp. This can be in seconds or milliseconds, the cmdlet defaults to interpreting this as milliseconds.
 
  .PARAMETER TimestampInSeconds
   Specifies that the timestamp should be interpreted in seconds.
 
  .EXAMPLE
   ConvertFrom-UnixTimestamp 1509494400000
 
   Converts the timestamp 1509494400000 to a DateTime which is Wednesday, November 1, 2017 12:00:00 AM.
 
  .INPUTS
   System.UInt64
 
  .OUTPUTS
   System.DateTime
 
  .NOTES
   AUTHOR: Michael Haken
   LAST UPDATE: 12/14/2017
 #>

    [CmdletBinding()]
    [OutputType([System.DateTime])]
    Param(
        [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)]
        [System.UInt64]$Timestamp,

        [Parameter()]
        [Switch]$TimestampInSeconds
    )

    Begin {
    }

    Process {

        [System.DateTime]$Epoch = New-Object -TypeName System.DateTime(1970, 1, 1, 0, 0, 0, [System.DateTimeKind]::Utc)

        if ($TimestampInSeconds)
        {
            Write-Output -InputObject ($Epoch.AddSeconds($Timestamp))
        }
        else
        {
            Write-Output -InputObject ($Epoch.AddMilliseconds($Timestamp))
        }
    }

    End {
    }
}

Function ConvertTo-UnixTimestamp {
    <#
  .SYNOPSIS
   Converts a DateTime object to a Unix timestamp.
   
  .DESCRIPTION
   The cmdlet converts a DateTime object to a unix timestamp in milliseconds or seconds past the epoch. It defaults to milliseconds.
   
  .PARAMETER Timestamp
   The DateTime object to convert. It will be converted to UTC and then translated.
 
  .PARAMETER OutputSeconds
   Specifies that output should be in seconds past the epoch instead of milliseconds
 
  .EXAMPLE
   ConvertTo-UnixTimestamp ([System.DateTime]::UtcNow)
 
   Converts the current time to a unix timestamp in milliseconds.
 
  .INPUTS
   System.DateTime
 
  .OUTPUTS
   System.UInt64
 
  .NOTES
   AUTHOR: Michael Haken
   LAST UPDATE: 12/14/2017
 #>

    [CmdletBinding()]
    [OutputType([System.DateTime])]
    Param(
        [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)]
        [System.DateTime]$Timestamp,

        [Parameter()]
        [Switch]$OutputSeconds
    )

    Begin {
    }

    Process {

        [System.DateTime]$Epoch = New-Object -TypeName System.DateTime(1970, 1, 1, 0, 0, 0, [System.DateTimeKind]::Utc)

        if ($OutputSeconds)
        {
            Write-Output -InputObject ([System.UInt64][System.Math]::Round(($Timestamp - $Epoch).TotalSeconds))
        }
        else
        {
            Write-Output -InputObject ([System.UInt64][System.Math]::Round(($Timestamp - $Epoch).TotalMilliseconds))
        }
    }

    End {
    }
}

#endregion


#region Dynamic Code

Function Import-Assembly {
    <#
  .SYNOPSIS
   Loads an assembly into the current session.
 
  .DESCRIPTION
   This cmdlet loads an assembly with the provided name if it is not already loaded.
 
  .PARAMETER AssemblyName
   The name of the assembly to load.
 
  .EXAMPLE
   Import-Assembly -AssemblyName System.Security
 
   Imports System.Security to the current PowerShell session.
 
  .INPUTS
   System.String
 
  .OUTPUTS
   None
 
  .NOTES
   AUTHOR: Michael Haken    
   LAST UPDATE: 1/25/2018
 #>

    [CmdletBinding()]
    [OutputType()]
    Param(
        [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)]
        [ValidateNotNullOrEmpty()]
        [System.String]$AssemblyName
    )

    Begin {

    }

    Process {
        $Names = [System.AppDomain]::CurrentDomain.GetAssemblies() | Select-Object -Property @{"Name" = "Name"; "Expression" = { $_.FullName.Split(",")[0] }} | Select-Object -ExpandProperty Name

        if ($Names -inotcontains $AssemblyName)
        {
            Write-Verbose -Message "Loading assembly $AssemblyName."
            [System.Reflection.Assembly]::LoadWithPartialName($AssemblyName) | Out-Null
        }
        else
        {
            Write-Verbose -Message "Assembly $AssemblyName is already loaded."
        }
    }

    End {
    }
}

#endregion

$script:UnboundExtensionMethod = @"
using System;
using System.Collections;
using System.Management.Automation;
using System.Reflection;
 
namespace BAMCIS.PowerShell.Common
{
    public static class ExtensionMethods
    {
        private static readonly BindingFlags Flags = BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public;
 
        public static T GetUnboundParameterValue<T>(this PSCmdlet cmdlet, string paramName, int unnamedPosition = -1)
        {
            if (cmdlet != null)
            {
                // If paramName isn't found, value at unnamedPosition will be returned instead
                object Context = GetPropertyValue(cmdlet, "Context");
                object Processor = GetPropertyValue(Context, "CurrentCommandProcessor");
                object ParameterBinder = GetPropertyValue(Processor, "CmdletParameterBinderController");
                IEnumerable Args = GetPropertyValue(ParameterBinder, "UnboundArguments") as System.Collections.IEnumerable;
 
                if (Args != null)
                {
                    bool IsSwitch = typeof(SwitchParameter) == typeof(T);
                    string CurrentParameterName = String.Empty;
                    int i = 0;
 
                    foreach (object Arg in Args)
                    {
 
                        //Is the unbound argument associated with a parameter name
                        object IsParameterName = GetPropertyValue(Arg, "ParameterNameSpecified");
 
                        //The parameter name for the argument was specified
                        if (IsParameterName != null && true.Equals(IsParameterName))
                        {
                            string ParameterName = GetPropertyValue(Arg, "ParameterName") as string;
                            CurrentParameterName = ParameterName;
 
                            //If it's a switch parameter, there won't be a value following it, so just return a present switch
                            if (IsSwitch && String.Equals(CurrentParameterName, paramName, StringComparison.OrdinalIgnoreCase))
                            {
                                return (T)(object)new SwitchParameter(true);
                            }
 
                            //Since we have a current parameter name, the next value in Args should be the value supplied
                            //to the argument, so we can head on to the next iteration, this skips the remaining code below
                            //and starts the next item in the foreach loop
                            continue;
                        }
 
                        //We assume the previous iteration identified a parameter name, so this must be its
                        //value
                        object ParameterValue = GetPropertyValue(Arg, "ArgumentValue");
 
                        //If the value we have grabbed had a parameter name specified,
                        //let's check to see if it's the desired parameter
                        if (CurrentParameterName != String.Empty)
                        {
                            //If the parameter name currently being assessed is equal to the provided param
                            //name, then return the value of the param
                            if (CurrentParameterName.Equals(paramName, StringComparison.OrdinalIgnoreCase))
                            {
                                return ConvertParameter<T>(ParameterValue);
                            }
                            else
                            {
                                //Since this wasn't the parameter name we were looking for, clear it out
                                CurrentParameterName = String.Empty;
                            }
                        }
                        //Otherwise there wasn't a parameter name, so the argument must have been supplied positionally,
                        //check if the current index is the position whose value we want
                        //Since positional parameters have to be specified first, this will be evaluated and increment until
                        //we run out of parameters or find a parameter with a name/value
                        else if (i++ == unnamedPosition)
                        {
                            //Just return the parameter value if the position matches what was specified
                            return ConvertParameter<T>(ParameterValue);
                        }
                    }
                }
 
                return default(T);
            }
            else
            {
                throw new ArgumentNullException("cmdlet", "The PSCmdlet cannot be null.");
            }
        }
 
        private static object GetPropertyValue(object instance, string fieldName)
        {
            // any access of a null object returns null.
            if (instance == null || String.IsNullOrEmpty(fieldName))
            {
                return null;
            }
 
            try
            {
                PropertyInfo PropInfo = instance.GetType().GetProperty(fieldName, Flags);
             
                if (PropInfo != null)
                {
                    try
                    {
                        return PropInfo.GetValue(instance, null);
                    }
                    catch (Exception) { }
                }
 
                // maybe it's a field
                FieldInfo FInfo = instance.GetType().GetField(fieldName, Flags);
 
                if (FInfo != null)
                {
                    try
                    {
                        return FInfo.GetValue(instance);
                    }
                    catch { }
                }
            }
            catch (Exception) { }
 
            // no match, return null.
            return null;
        }
     
        private static T ConvertParameter<T>(this object value)
        {
            if (value == null || object.Equals(value, default(T)))
            {
                return default(T);
            }
 
            PSObject PSObj = value as PSObject;
 
            if (PSObj != null)
            {
                return PSObj.BaseObject.ConvertParameter<T>();
            }
 
            if (value is T)
            {
                if (typeof(T) == typeof(string))
                {
                    //Remove quotes from string values taken from the command line
                    // value = value.ToString().Trim('"').Trim('\'');
                }
                return (T)value;
            }
 
            var constructorInfo = typeof(T).GetConstructor(new[] { value.GetType() });
 
            if (constructorInfo != null)
            {
                return (T)constructorInfo.Invoke(new[] { value });
            }
 
            try
            {
                return (T)Convert.ChangeType(value, typeof(T));
            }
            catch (Exception)
            {
                return default(T);
            }
        }
    }
}
"@