Convert-Etl2Pcapng.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
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.

<#
Convert-Etl2Pcapng
 
A PowerShell wrapper for etl2pcapng, which converts packet captures
in ETL format generated by ndiscap (the ETW provider in Windows that
produces packet capture events) to pcapng format (readable by Wireshark).
#>


################
### ###
### PUBLIC ###
### ###
################

#region PUBLIC

# FUNCTION : Register-Etl2Pcapng
# PURPOSE : Registers the ecript to ETL files
function Register-Etl2Pcapng 
{
    <#
    .SYNOPSIS
        Adds a right-click menu option in Windows for etl2pcapng.
    .DESCRIPTION
        Registers a shell context menu item for Convert-Etl2Pcapng. Right-clicking on an ETL fill will show an option "Convert with etl2pcapng". This will execute Convert-Etl2Pcapng with default settings against the ETL file.
    .EXAMPLE
        Register-Etl2Pcapng
 
        Registers the "Convert with etl2pcapng" shell menu item.
    .NOTES
        Author: Microsoft Edge OS Networking Team and Microsoft CSS
        Please file issues on GitHub @ https://github.com/microsoft/Convert-Etl2Pcapng
    .LINK
        More projects : https://github.com/topics/msftnet
        Windows Networking Blog : https://blogs.technet.microsoft.com/networking/
    #>


    [CmdletBinding()]
    param (
        # Causes the explorer menu option, "Convert with etl2pcapng", to not exit the command prompt when complete and output Verbose logging.
        [switch]$UseVerbose,
        # Causes the explorer menu option, "Convert with etl2pcapng", to not exit the command prompt when complete and output Debug logging.
        [switch]$UseDebug
    )

    function New-RegKey 
    {
        [CmdletBinding()]
        param(
            [string]$path,
            [string]$type,
            $value
        )

        Write-Verbose "New-RegKey: Starting"
        # make sure the PSDrive to HKCR is created
        if (-NOT (Get-PSDrive -Name HKCR -EA SilentlyContinue)) 
        {
            New-PSDrive -Name HKCR -PSProvider Registry -Root HKEY_CLASSES_ROOT -Scope Local | Out-Null
        }

        # do the reg work
        try 
        {
            Write-Verbose "New-RegKey: Creating key $path"
            if ($type -eq "Directory") {
                New-Item $path -ItemType $type -Force -EA SilentlyContinue | Out-Null
            }
            else {
                Write-Verbose "New-RegKey: Setting property on $path to $value"
                Set-ItemProperty -LiteralPath $path -Name '(Default)' -Value $value -Force -EA SilentlyContinue | Out-Null
            }
        }
        catch 
        {
            Write-Error "New-RegKey: Failed to create $path."
            return $false
        }

        Write-Verbose "New-RegKey: Work complete!"
        return $true
    }

    Write-Verbose "Register-Etl2Pcapng: Work! Work!"

    # test for Admin access
    Write-Verbose "Register-Etl2Pcapng: Test admin rights."
    if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) 
    {
        Write-Error "Register-Etl2Pcapng: Administrator rights are needed to execute this command. Please run PowerShell as Administrator and try again."
        return $null
    }

    # make sure the module is installed, just in case
    Write-Verbose "Register-Etl2Pcapng: Verify this is running from the module."
    $isModFnd = Get-Module -ListAvailable Convert-ETL2PCAPNG -EA SilentlyContinue

    if (-NOT $isModFnd) {
        Write-Error "This cannot be run outside of the Convert-ETL2PCAPNG module. Please install the Convert-ETL2PCAPNG module first:`n`nInstall-Module Convert-ELT2PCAPNG."
        return $null
    }

    # create a PSDrive to HKEY_CLASSES_ROOT
    Write-Verbose "Register-Etl2Pcapng: Create PSDrive for HKEY_CLASSES_ROOT."
    if (-NOT (Get-PSDrive -Name HKCR -EA SilentlyContinue)) 
    {
        New-PSDrive -Name HKCR -PSProvider Registry -Root HKEY_CLASSES_ROOT -Scope Local | Out-Null
    }

    # create the shell extension for etl2pcapng
    Write-Verbose "Register-Etl2Pcapng: Add the Convert-Etl2Pcapng app to HKCR:\SystemFileAssociations\.etl to prevent possible conflicts."

    $rootPath = "HKCR:\SystemFileAssociations\.etl\shell\Convert-Etl2Pcapng"
    if (-NOT (New-RegKey "$rootPath\Command" Directory)) { Write-Error "Could not create directory in SystemFileAssociations."; exit }

    # create the command
    Write-Verbose "Register-Etl2Pcapng: Configure Convert-Etl2Pcapng."
    if (-NOT (New-RegKey $rootPath -value "Convert with etl2pcapng")) { Write-Error "Could not write menu text." }

    if ($UseVerbose) 
    {
        $cmd = 'cmd /k powershell -NoProfile -NonInteractive -NoLogo Convert-Etl2Pcapng ''%1'' -Verbose'
    }
    elseif ($UseDebug) 
    {
        $cmd = 'cmd /k powershell -NoProfile -NonInteractive -NoLogo Convert-Etl2Pcapng ''%1'' -Debug'
    }
    else 
    {
        $cmd = 'cmd /c powershell -NoProfile -NonInteractive -NoLogo Convert-Etl2Pcapng ''%1'''
    }

    Write-Verbose "Register-Etl2Pcapng: Add Convert-ETL2PCAPNG command: $cmd"
    if (-NOT (New-RegKey "$rootPath\Command" -Value $cmd)) { Write-Error "Could not write command to registry."; exit }

    # check for the ETL extenstion in HKCR, create if missing
    Write-Verbose "Register-Etl2Pcapng: Add the context item to .etl files."

    Write-Verbose "Register-Etl2Pcapng: Work complete!"
} #end Register-Etl2Pcapng


# FUNCTION : Unregister-Etl2Pcapng
# PURPOSE : Unregisters the ecript to ETL files
function Unregister-Etl2Pcapng 
{
    [CmdletBinding()]
    param()

    <#
    .SYNOPSIS
        Removes the right-click menu option in Windows for etl2pcapng.
    .DESCRIPTION
        Unregisters the shell context menu item for Convert-Etl2Pcapng. This will remove the option to right-click on an ETL file and select "Convert with etl2pcapng".
    .EXAMPLE
        Unregister-Etl2Pcapng
 
        Unregisters the "Convert with etl2pcapng" menu item.
    .NOTES
        Author: Microsoft Edge OS Networking Team and Microsoft CSS
        Please file issues on GitHub @ https://github.com/microsoft/Convert-Etl2Pcapng
    .LINK
        More projects : https://github.com/topics/msftnet
        Windows Networking Blog : https://blogs.technet.microsoft.com/networking/
    #>


    Write-Verbose "Unregister-Etl2Pcapng: Work! Work!"

    # test for Admin access
    Write-Verbose "Unregister-Etl2Pcapng: Test admin rights."
    if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) 
    {
        Write-Error "Unregister-Etl2Pcapng: Administrator rights are needed to execute this command. Please run PowerShell as Administrator and try again."
        return $null
    }

    # create a PSDrive to HKEY_CLASSES_ROOT
    Write-Verbose "Unregister-Etl2Pcapng: Creating HKCR PSDrive."
    if (-NOT (Get-PSDrive -Name HKCR -EA SilentlyContinue)) 
    {
        New-PSDrive -Name HKCR -PSProvider Registry -Root HKEY_CLASSES_ROOT -Scope Local | Out-Null
    }

    # check if the original version was registered and remove its components
    # remove the Convert-ETL2PCAPNG HKCR key
    $test = Get-Item "HKCR:\Convert-Etl2Pcapng" -EA SilentlyContinue
    if ($test)
    {
        Write-Verbose "Unregister-Etl2Pcapng: Removing Convert-Etl2Pcapng HKCR app."
        Remove-Item "HKCR:\Convert-Etl2Pcapng" -Recurse -Force -EA SilentlyContinue
    }

    $isOld = Get-ItemProperty -LiteralPath "HKCR:\.etl" -Name '(Default)' -EA SilentlyContinue
    if ($isOld.'(default)' -eq 'Convert-Etl2Pcapng')
    {
        # remove the default to .etl, but don't delete it
        Write-Verbose "Unregister-Etl2Pcapng: Cleanup .etl extension option."
        Set-ItemProperty -LiteralPath "HKCR:\.etl" -Name '(Default)' -Value "" -Force -EA SilentlyContinue
    }

    $test = Get-ItemProperty -LiteralPath "HKCR:\.etl" -Name 'Convert-Etl2Pcapng' -EA SilentlyContinue
    if ( $test )
    {
        Remove-ItemProperty -LiteralPath "HKCR:\.etl" -Name 'Convert-Etl2Pcapng' -Force 
    }

    # remove the SystemFileAssociation
    $rootPath = "HKCR:\SystemFileAssociations\.etl\shell\Convert-Etl2Pcapng"
    $testNew = Get-Item $rootPath -EA SilentlyContinue

    if ($testNew)
    {
        try 
        {
            Remove-Item $rootPath -Recurse -Force -ErrorAction Stop    
        }
        catch 
        {
            Write-Error "Unregister-Etl2Pcapng: Failed to cleanup the SystemFileAssociations."
        }
        
    }
    

    # clean up the user folder
    Write-Verbose "Unregister-Etl2Pcapng: Cleaning up LocalAppData directory."
    $settings = Get-E2PSettings
    try 
    {
        Remove-Item $settings.appDataPath -Force -Recurse -EA Stop    
    }
    catch 
    {
        Write-Error "Unregister-Etl2Pcapng: Failed to cleanup the LocalAppData: $($settings.appDataPath)"
    }
    
    Write-Verbose "Unregister-Etl2Pcapng: Work complete!"
} #end Unregister-Etl2Pcapng


# FUNCTION : Convert-Etl2Pcapng
# PURPOSE : Executes ETL2PCAPNG
function Convert-Etl2Pcapng 
{
    <#
    .SYNOPSIS
        ndiscap tracing is the built-in packet capture tool used in Windows. ETL files cannot be read by third-party tools like Wireshark. Etl2pcapng converts ndiscap packet captures to a format readable by Wireshark.
    .DESCRIPTION
        This script converts ndiscap packets in an ETL into a Wireshark readable pcapng file.
    .PARAMETER Path
        The path to the ETL file or path containing the ETL file(s). When a container/directory is provided the script will search the partent directory for ETL files to convert.
    .PARAMETER Out
        The output path for the files. This parameter is optional. By default the script saves to the same directory the ETL file is located in.
    .PARAMETER Recurse
        Searches through child containers/directories for ETL files. Only valid when Path is a directory.
    .EXAMPLE
        Convert-Etl2Pcapng -Path C:\traces -Out D:\temp -Recurse
 
        Searches through C:\traces and all child directories for ETL files. The converted PCAPNG files will be saved to D:\temp.
    .EXAMPLE
        Convert-LBFO2Set C:\traces
 
        Converts all ETL files in C:\traces, but not any child directories, for ETLs and saves the PCAPNG files to the same directory (C:\traces).
    .NOTES
        Author: Microsoft Edge OS Networking Team and Microsoft CSS
        Please file issues on GitHub @ https://github.com/microsoft/Convert-Etl2Pcapng
    .LINK
        More projects : https://github.com/topics/msftnet
        Windows Networking Blog : https://blogs.technet.microsoft.com/networking/
    #>


    [CmdletBinding(DefaultParameterSetName = 'LiteralPath')]
    param (
        # Path accepts a literal string path.
        [parameter( Position = 0,
            ParameterSetName = 'LiteralPath',
            HelpMessage = 'Enter one or more filenames as a string',
            ValueFromPipeline = $false )]
        [string]
        $Path,

        # PSPath accepts a FileSystemInfo object from cmdlets like Get-Item and Get-ChildItem. Accepts pipeline input.
        [parameter( Position = 0,
            ParameterSetName = 'Path',
            HelpMessage = 'Enter one or more filenames as a string',
            ValueFromPipeline = $true )]
        [System.IO.FileSystemInfo]
        $PSPath,

        [parameter( Position = 1,
            ParameterSetName = 'Path',
            ValueFromPipeline = $false )]
        [parameter( Position = 1,
            ParameterSetName = 'LiteralPath',
            ValueFromPipeline = $false )]
        [string]
        $Out = $null,

        [parameter( Mandatory = $false,
            ParameterSetName = 'Path',
            ValueFromPipeline = $false )]
        [parameter( Mandatory = $false,
            ParameterSetName = 'LiteralPath',
            ValueFromPipeline = $false )]
        [switch]
        $Recurse
    )

    Write-Verbose "Convert-Etl2Pcapng: Work! Work!"

    ### Validating paths and parameters ###
    # check the path param
    Write-Verbose "Convert-Etl2Pcapng: Validate Path."
    if ($PSPath -is [System.IO.FileSystemInfo]) 
    {
        $isPathFnd = $PSPath
    }
    else 
    {
        $isPathFnd = Get-Item $Path -EA SilentlyContinue    
    }
    
    # if a dir/container, then look for ETL files
    if ($isPathFnd) 
    {
        # is this a container/directory
        if ($isPathFnd.PSisContainer) 
        {
            Write-Verbose "Convert-Etl2Pcapng: Searching for ETL files in $($isPathFnd.FullName)."
            # look for ETL files
            if ($Recurse) 
            {
                Write-Verbose "Convert-Etl2Pcapng: Dir with child container recurse."
                [array]$etlFiles = Get-ChildItem $isPathFnd.FullName -Filter "*.etl" -Recurse -Force -ErrorAction SilentlyContinue
            }
            else 
            {
                Write-Verbose "Convert-Etl2Pcapng: Dir with no child containers."
                [array]$etlFiles = Get-ChildItem $isPathFnd.FullName -Filter "*.etl" -Force -ErrorAction SilentlyContinue
            }
        }
        elseif ($isPathFnd.Extension -eq ".etl") 
        {
            Write-Verbose "Convert-Etl2Pcapng: Single file."
            [array]$etlFiles = $isPathFnd
        }
    }

    # exit if no ETL file(s) found
    if (-NOT $etlFiles) 
    {
        if ($PSPath -is [System.IO.FileSystemInfo]) 
        {
            Write-Error "Convert-Etl2Pcapng: Failed to find a valid ETL file. Path: $($PSPath.FullName)"
        }
        else 
        {
            Write-Error "Convert-Etl2Pcapng: Failed to find a valid ETL file. Path: $Path"
        }
        return $null
    }

    # make sure $Out is a valid location
    if ($Out) 
    {
        Write-Verbose "Convert-Etl2Pcapng: Validate Out."

        if (-NOT (Test-Path $Out -IsValid)) 
        {
            Write-Error "Convert-Etl2Pcapng: The Out path is an invalid path. Out: $Out"
            return $null
        }

        # create the dir if it's not there
        $isOutFnd = Get-Item $Out -EA SilentlyContinue
        if (-NOT $isOutFnd) 
        {
            try {
                Write-Verbose "Convert-Etl2Pcapng: Creating output path $Out"
                New-Item $Out -ItemType Directory -Force -EA Stop | Out-Null
            }
            catch {
                Write-Error "Convert-Etl2Pcapng: Failed to create Out directory at $Out. Error: $($error[0].ToString())"
            }
        }
    }


    ### get the path to etl2pcapng.exe
    Write-Verbose "Convert-Etl2Pcapng: Getting for etl2pcapng location."
    $e2pPath = Update-Etl2Pcapng

    # validate etl2pcapng is actually there and strip out the parent dir
    if ($e2pPath) 
    {
        $isE2PFnd = Get-Item $e2pPath -EA SilentlyContinue

        if ($isE2PFnd) {
            $e2pDir = $isE2PFnd.DirectoryName
        }
        else {
            Write-Error "Convert-Etl2Pcapng: Failed to locate etl2pcanpng.exe."
            return $null
        }
    }

    #### Finally do the conversion work ####
    Write-Verbose "Convert-Etl2Pcapng: Starting ETL to PCAPNG conversion(s)."
    Push-Location $e2pDir
    foreach ($file in $etlFiles) 
    {
        if ($Out) 
        {
            Write-Verbose "Convert-Etl2Pcapng: Converting $($file.FullName) to $Out\$($file.BaseName).pcapng"
            .\etl2pcapng.exe "$($file.FullName)" "$Out\$($file.BaseName).pcapng"
        }
        else 
        {
            Write-Verbose "Convert-Etl2Pcapng: Converting $($file.FullName) to $($file.DirectoryName)\$($file.BaseName).pcapng"
            .\etl2pcapng.exe "$($file.FullName)" "$($file.DirectoryName)\$($file.BaseName).pcapng"
        }
    }
    Pop-Location

    Write-Verbose "Convert-Etl2Pcapng: Work complete!"
} #end Convert-Etl2Pcapng



# FUNCTION : Update-Etl2Pcapng
# PURPOSE : Gets the newest version of ETL2PCAPNG
function Update-Etl2Pcapng 
{
    [CmdletBinding()]
    param([switch]$Force)

    <#
     # Check for etl2pcapng updates only once a week
     #
     # The last time an update was checked for is located
     # in the module directory under settings.xml.
     #
     # The -Force param causes an etl2pcapng update check regardless of the last date checked.
     #
     #>



    Write-Verbose "Update-Etl2Pcapng - Starting"

    # check if etlpcapng is already downloaded - do not use pwsh terney to maintain Windows PowerShell backwards compatibilty!
    if ([System.Environment]::Is64BitOperatingSystem) 
    {
        $arch = "x64"
    }
    else {
        $arch = "x86"    
    }

    Write-Verbose "Update-Etl2Pcapng - OS architecture is $arch."

    # read settings.xml
    $settings = Get-E2PSettings

    Write-Verbose "Update-Etl2Pcapng - Settings:`n`n$($settings | Format-List | Out-String)`n`n"

    # store app data path in an easier to use var
    $here = $settings.appDataPath

    Write-Verbose "Update-Etl2Pcapng - Timestamps:`nCurrent date:`t$((Get-Date).Date)`nSettings date:`t$($settings.LastUpdate.Date)`n"

    # check for an update when -Force set or it's been 7 days since we last checked
    if ($Force -or ((Get-Date).Date.AddDays(-7) -gt $settings.LastUpdate.Date)) 
    {
        Write-Verbose "Update-Etl2Pcapng - Checking for an update to etl2pcapng."

        Write-Verbose "Update-Etl2Pcapng - Getting etl2pcapng releases from GitGub."        
        $repo = 'microsoft/etl2pcapng' 

        try
        {
            $latest = Find-GitReleaseLatest $repo -EA Stop            
        }
        catch
        {
            return (Write-Error "Failed to retrieve the latest release from repo: $repo" -EA Stop)
        }
        
        Write-Verbose "Update-Etl2Pcapng - The latest release is:`n`n$($latest | Format-Table | Out-String)"

        if ($latest.Version -gt $settings.CurrVersion) 
        {
            Write-Verbose "Update-Etl2Pcapng - Cleaning up existing files."
            # delete existing zip file
            $isZipFnd = Get-Item "$here\etl2pcapng.zip" -EA SilentlyContinue
            if ($isZipFnd) { Remove-Item "$here\etl2pcapng.zip" -Force | Out-Null }
            
            # make sure VC Redist is installed
            Write-Verbose "Update-Etl2Pcapng - Checking for Visual Studio C++ Redistribution install."

            <#
            # vcdist no longer needed as of version 1.5.0
            #look for VS C++ 2015-2019
            $isVCRedistFnd = Find-E2PSoftware "Microsoft Visual C\+\+ 2015-2019 Redistributable \($arch\)"
             
            if (-NOT $isVCRedistFnd -and ())
            {
                if ($arch -eq "x64")
                {
                    $URI = $settings.vcredist64Uri
                }
                else
                {
                    $URI = $settings.vcredist32Uri
                }
 
                Write-Verbose "Update-Etl2Pcapng - Downloading Microsoft Visual C\+\+ 2015-2019 Redistributable from $URI`."
 
                # download vcredist
                try
                {
                    $dl = Get-WebFile -Uri $URI -savePath "$here" -fileName "vcredist.exe" -EA Stop
                }
                catch
                {
                    return (Write-Error "Update-Etl2Pcapng - Microsoft Visual C`+`+ 2015-2019 Redistributable `($arch`) is not installed and could not be downloaded. Please manually download and install from $URI before using etl2pcapng. Error: $_" -EA Stop)
                }
 
                # try to install vcredist
                try
                {
                    Push-Location $here
                    Write-Verbose "Update-Etl2Pcapng - Installing Microsoft Visual C\+\+ 2015-2019 Redistributable."
                    .\vcredist.exe /install /quiet /log "$here\Install_vc_redist_2017_x64.log"
                }
                catch
                {
                    return (Write-Error "Update-Etl2Pcapng - Failed to install Microsoft Visual C`+`+ 2015-2019 Redistributable `($arch`). Please download from $URI and install before continuing." -EA Stop)
                }
                finally
                {
                    # cleanup
                    Pop-Location
                    Start-Sleep 1
                    Remove-Item "$here\vcredist.exe" -Force -EA SilentlyContinue | Out-Null
                }
 
                # only cleanup the log file if the install succeeds and we don't need it
                Remove-Item "$here\Install*.log" -Force -EA SilentlyContinue | Out-Null
                Write-Verbose "Update-Etl2Pcapng - VC redist installed."
            }
            #>

            
            
            # remove the existing etl2pcapng
            $isDirFnd = Get-Item "$here\etl2pcapng" -EA SilentlyContinue

            ### There is a -Recurse bug here when using OneDrive sync'ed dirs.
            ### It is supposed to be fixed in pwsh 7, but it's not.
            ### This should not be an issue for production since this should be run from a %LocalAppData%, not OneDrive.
            ### https://github.com/PowerShell/PowerShell/issues/9461

            if ($isDirFnd) { Remove-Item $isDirFnd.FullName -Recurse -Force -EA SilentlyContinue | Out-Null }

            Write-Verbose "Update-Etl2Pcapng - Downloading etl2pcapng"
            # grab the etl2pcapng tags page from GitHub
            try 
            {
                $e2pPath = Get-WebFile -Uri $latest.URL -savePath "$here" -fileName "etl2pcapng.zip" -EA Stop
            }
            catch 
            {
                return (Write-Error "Update-Etl2Pcapng - Cannot reach the etl2pcapng GitHub page: $_" -EA Stop)
            }
        
            # extract and overwrite
            Write-Verbose "Update-Etl2Pcapng - Extracting the etl2pcapng archive."
            try 
            {
                Expand-Archive "$e2pPath" $here -Force -EA Stop    
            }
            catch 
            {
                return (Write-Error "Update-Etl2Pcapng - Could not extract etl2pcapng. Error: $_" -EA Stop)
            }
            
            # cleanup the zip
            Write-Verbose "Update-Etl2Pcapng - Cleaning up the zip file."
            $isZipFnd = Get-Item "$e2pPath" -EA SilentlyContinue
            if ($isZipFnd) { Remove-Item "$e2pPath" -Force -EA SilentlyContinue | Out-Null }

            # update the installed version
            Write-Verbose "Update-Etl2Pcapng - Updating version in settings to $($latest.Version)"
            $settings.SetCurrVersion(($latest.Version))
        }

        # update Settings.LastUpdate
        $updateTime = (Get-Date).Date.ToUniversalTime()
        Write-Verbose "Update-Etl2Pcapng - Updating last update check in settings to $($updateTime.ToString())"
        $settings.SetLastUpdate($updateTime)
        
        Write-Verbose "Update-Etl2Pcapng - Saving E2P settings changes."
        Set-E2PSettings $settings
    }

    
    $isE2PFnd = Get-Item "$here\etl2pcapng\$arch\etl2pcapng.exe" -EA SilentlyContinue

    
    if ($isE2PFnd) 
    {
        Write-Verbose "Update-Etl2Pcapng - Returning etl2pcapng.exe at $here\etl2pcapng\$arch\etl2pcapng.exe"
        Write-Verbose "Update-Etl2Pcapng - Work complete."
        return ("$here\etl2pcapng\$arch\etl2pcapng.exe")
    }
    else 
    {
        Write-Verbose "Update-Etl2Pcapng - Failed to find or download etl2pcapng.exe."
        Write-Verbose "Update-Etl2Pcapng - Work complete."
        return $null    
    }

} #end Update-Etl2Pcapng

#endregion PUBLIC


#################
### ###
### PRIVATE ###
### ###
#################

#region AUX
##### AUX functions that are not exported #####

# FUNCTION : Get-E2PSettings
# PURPOSE : Finds and returns the module settings
function Get-E2PSettings 
{
    Write-Verbose "Get-E2PSettings - Starting"

    $setPath = "$(Find-E2PPath)\settings.xml"

    # is there a settings file at the appDataPath location?
    $isADP = Get-Item $setPath -ErrorAction SilentlyContinue

    # read the file if it exists
    if ($isADP) 
    {
        Write-Verbose "Get-E2PSettings - Settings file found. Getting settings from file."
        # read the settings file
        try 
        {
            $settings = [E2PSettings]::New((Import-Clixml "$setPath"))    
        }
        catch 
        {
            return (Write-Error "Failed to import settings: $_" -EA Stop)
        }
        

        # return the settings
        Write-Verbose "Get-E2PSettings - Work complete!"
        return $settings

        # create the file if it does not exist
    }
    else 
    {
        # create the etl2pcapng dir
        Write-Verbose "Get-E2PSettings - Settings file not found. Using defaults."
        $settings = New-E2PSetting

        # write the settings JSON file
        Set-E2PSettings $settings
        
        # return default settings
        Write-Verbose "Get-E2PSettings - Work complete!"
        return $settings
    }
    Write-Verbose "Get-E2PSettings - Something unexpected went wrong and no settings were returned."
    Write-Verbose "Get-E2PSettings - Work complete!"
    return $null
} #end Get-E2PSettings


# FUNCTION : Set-E2PSettings
# PURPOSE : Updates E2P settings
function Set-E2PSettings
{
    [CmdletBinding()]
    param (
        [PSCustomObject]$settings
    )

    try 
    {
        $settings.Save("$($settings.appDataPath)\settings.xml")
    }
    catch 
    {
        return (Write-Error "Failed to write settings.xml to $($settings.appDataPath): $_" -EA Stop)
    }

    return $null
}


function New-E2PSetting
{
    [string]$here = Find-E2PPath

    # create default settings
    $defSettings = [E2PSettings]::New($here)
        
    return $defSettings
}


function Find-E2PPath
{
    # first try to get the module in use
    $mods = Get-Module Convert-Etl2Pcapng -EA SilentlyContinue
    
    # the backup plan
    if (-NOT $mods)
    {
        $mods = Get-Module -ListAvailable Convert-Etl2Pcapng

        if ($mods -is [array])
        {
            # look for the current user module
            if ($PSHost.Version.Major -ge 6)
            {
                $here = Split-Path -Parent ($mods | Where-Object Path -match "^.*(?:$env:UserName).*(?!:WindowsPowerShell)").Path
            }
            else 
            {
                $here = Split-Path -Parent ($mods | Where-Object Path -match "^.*(?:$env:UserName).*(?:WindowsPowerShell)").Path
            }

            # if that failed, pick the first item on the list and use that
            if (-NOT $here)
            {
                $here = Split-Path -Parent $mods[0].Path
            }
        }
        else
        {
            $here = Split-Path -Parent $mods.Path
        }
    }
    else
    {
        $here = Split-Path -Parent $mods.Path
    }

    return $here
}


# FUNCTION: Get-WebFile
# PURPOSE:
function Get-WebFile
{
    param ( 
        [string]$URI,
        [string]$savePath,
        [string]$fileName
    )

    Write-Verbose "Get-WebFile - Begin"
    Write-Verbose "Get-WebFile - Attempting to download: $dlUrl"

    # make sure we don't try to use an insecure SSL/TLS protocol when downloading files
    $secureProtocols = @() 
    $insecureProtocols = @( [System.Net.SecurityProtocolType]::SystemDefault, 
                            [System.Net.SecurityProtocolType]::Ssl3, 
                            [System.Net.SecurityProtocolType]::Tls, 
                            [System.Net.SecurityProtocolType]::Tls11) 
    foreach ($protocol in [System.Enum]::GetValues([System.Net.SecurityProtocolType])) 
    { 
        if ($insecureProtocols -notcontains $protocol) 
        { 
            $secureProtocols += $protocol 
        } 
    } 
    [System.Net.ServicePointManager]::SecurityProtocol = $secureProtocols

    try 
    {
        Invoke-WebRequest -Uri $URI -OutFile "$savePath\$fileName"
    } 
    catch 
    {
        return (Write-Error "Could not download $URI`: $($Error[0].ToString())" -EA Stop)
    }

    Write-Verbose "Get-WebFile - File saved to: $savePath\$fileName"
    Write-Verbose "Get-WebFile - End"
    return "$savePath\$fileName"
} #end Get-WebFile


# FUNCTION: Find-GitReleaseLatest
# PURPOSE: Calls Github API to retrieve details about the latest release. Returns a PSCustomObject with repro, version (tag_name), and download URL.
function Find-GitReleaseLatest
{
    [CmdletBinding()]
    param(
        [string]$repo
    )

    Write-Verbose "Find-GitReleaseLatest - Begin"

    $baseApiUri = "https://api.github.com/repos/$($repo)/releases/latest"


    # get the available releases
    Write-Verbose "Find-GitReleaseLatest - Processing repro: $repo"
    Write-Verbose "Find-GitReleaseLatest - Making Github API call to: $baseApiUrl"
    try 
    {
        if ($pshost.Version.Major -le 5)
        {
            $rawReleases = Invoke-WebRequest $baseApiUri -UseBasicParsing -EA Stop
        }
        elseif ($pshost.Version.Major -ge 6)
        {
            $rawReleases = Invoke-WebRequest $baseApiUri -EA Stop
        }
        else 
        {
            return (Write-Error "Unsupported version of PowerShell...?" -EA Stop)
        }
    }
    catch 
    {
        return (Write-Error "Could not get GitHub releases. Error: $_" -EA Stop)        
    }

    Write-Verbose "Find-GitReleaseLatest - Processing results."
    try
    {
        [version]$version = ($rawReleases.Content | ConvertFrom-Json).tag_name
    }
    catch
    {
        $version = ($rawReleases.Content | ConvertFrom-Json).tag_name
    }

    Write-Verbose "Find-GitReleaseLatest - Found version: $version"

    $dlURI = ($rawReleases.Content | ConvertFrom-Json).Assets.browser_download_url

    Write-Verbose "Find-GitReleaseLatest - Found download URL: $dlURI"

    Write-Verbose "Find-GitReleaseLatest - End"

    return ([PSCustomObject]@{
        Repo    = $repo
        Version = $version
        URL     = $dlURI
    })
} #end Find-GitReleaseLatest




# FUNCTION: Find-E2PSoftware
# PURPOSE: Gets a list of all installed software from the registry with optional filter on the DisplayName.

function Find-E2PSoftware 
{
    [CmdletBinding()]
    param ($displayFilter = $null)

    Write-Verbose "Find-E2PSoftware - Begin"

    $apps = @()
    
    [string[]]$regPaths = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall", "HKLM:\SOFTWARE\Wow6432node\Microsoft\Windows\CurrentVersion\Uninstall"
      
    foreach ($regPath in $regPaths) 
    { 
      
        Write-Verbose "Find-E2PSoftware: Checking Path: $regPath"

        try 
        { 
            $reg = Get-Item $regPath -ErrorAction Stop
        }
        catch 
        { 
            Write-Debug "Find-E2PSoftware: Could not find the path: $_ `n`n $reg "
            continue 
        } 
      

        # change the EAP to stop to force the try to fail if there is an error
        $ErrorActionPreference = "SilentlyContinue"

        # get all the child keys
        [array]$regkeys = Get-ChildItem $regPath

        #echo "$($regKeys.PSChildName | Out-String)"
      
        foreach ($key in $regkeys) 
        {   
            Write-Verbose "Find-E2PSoftware: $($key.PSChildName)"
                
            if ($displayFilter) 
            {
                Write-Verbose "Find-E2PSoftware: Filter $((Get-ItemProperty -Path $key.PsPath -Name DisplayName).DisplayName) match $displayFilter"
                if ( "$((Get-ItemProperty -Path $key.PsPath -Name DisplayName).DisplayName)" -match $displayFilter) 
                {
                    # create the PsCustomObject that stores software details
                    $tmpObj = [pscustomobject]@{
                        Name = $key.PSChildName
                    }
        
                    # loop through all the properties and add them to the object
                    $key.Property | ForEach-Object {
                         
                        $tmpObj | Add-Member -Name $_ -MemberType NoteProperty -Value "$((Get-ItemProperty -Path $key.PsPath -Name $_)."$_")"
                    }
        
                    # add the software to the apps array
                    $apps += $tmpObj
                    Remove-Variable tmpObj
                }
            }
            else 
            {
                $tmpObj = [pscustomobject]@{
                    Name = $key.PSChildName
                }
    
                $key.Property | ForEach-Object {
                     
                    $tmpObj | Add-Member -Name $_ -MemberType NoteProperty -Value "$((Get-ItemProperty -Path $key.PsPath -Name $_)."$_")"
                }
    
                # add the software to the apps array
                $apps += $tmpObj
                Remove-Variable tmpObj
            }
        }
    }

    Write-Verbose "Find-E2PSoftware: Work complete!"
    return $apps     
} #end Find-E2PSoftware


class E2PSettings
{
    [datetime]$LastUpdate
    [version]$CurrVersion
    [string]$appDataPath

    #region construtors
    E2PSettings()
    {
        $this.LastUpdate    = [datetime]::FromFileTimeUtc(0)
        $this.CurrVersion   = [version]::new()
        $this.appDataPath   = $null
    }

    E2PSettings([string]$path)
    {
        $this.LastUpdate    = [datetime]::FromFileTimeUtc(0)
        $this.CurrVersion   = [version]::new()
        $this.appDataPath   = $path
    }

    E2PSettings([PSCustomObject]$set)
    {
        $this.LastUpdate    = $set.LastUpdate
        $this.CurrVersion   = $set.CurrVersion
        $this.appDataPath   = $set.appDataPath
    }
    #endregion construtors

    #region getters
    [datetime]GetLastUpdate()
    {
        return ($this.LastUpdate)
    }

    [version]GetCurrVersion()
    {
        return ($this.CurrVersion)
    }

    [string]GetAppDataPath()
    {
        return ($this.appDataPath)
    }
    #endregion getters


    #region setters
    SetLastUpdate([datetime]$LastUpdate)
    {
        $this.LastUpdate = $LastUpdate
    }

    SetCurrVersion([version]$CurrVersion)
    {
        $this.CurrVersion = $CurrVersion
    }

    SetAppDataPath([string]$appDataPath)
    {
        $this.appDataPath = $appDataPath
    }
    #endregion setters


    #region methods
    [string]ToString()
    {
        return (@"
LastUpdate : $($this.appDataPath)
CurrVersion : $($this.CurrVersion)
appDataPath : $($this.appDataPath)
"@
)
    }

    # by returning an ErrorRecord the Save method can create a terminating error in a caller using a try-catch
    [System.Management.Automation.ErrorRecord]
    Save($Filename)
    {
        # convert the filename to a string if we get a filesystem object from something like Get-Item
        if ($Filename -is [System.IO.FileSystemInfo])
        {
            $Filename = $Filename.Fullname
        }

        # make sure the file is valid
        if (-NOT (Test-Path "$Filename" -IsValid))
        {
            # return a terminating error
            return (Write-Error "[E2PSettings].Save - The filename is invalid: $Filename" -EA Stop)
        }

        # no check if the file exists. This function explicitly overwrites the existing content

        try 
        {
            $this | Export-Clixml -Path "$Filename" -Depth 20 -Encoding utf8 -Force -EA Stop
        }
        catch 
        {
            # return a terminating error
            return (Write-Error "[E2PSettings].Save - Could not save the settings file: $_" -EA Stop)
        }

        # return a nonterminating null
        return $null
    }

    #endregion methods
}



#endregion AUX

# the list of functions the module will export.
Export-ModuleMember -Function Register-Etl2Pcapng
Export-ModuleMember -Function Unregister-Etl2Pcapng
Export-ModuleMember -Function Convert-Etl2Pcapng
Export-ModuleMember -Function Update-Etl2Pcapng