Dictionaries/Dict.Windows/Dict.Windows.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
<#
 
  ###### ####### ## ## ######## ## ## ######## ######## ########
 ## ## ## ## ### ### ## ## ## ## ## ## ## ##
 ## ## ## #### #### ## ## ## ## ## ## ## ##
 ## ## ## ## ### ## ######## ## ## ## ###### ########
 ## ## ## ## ## ## ## ## ## ## ## ##
 ## ## ## ## ## ## ## ## ## ## ## ## ##
  ###### ####### ## ## ## ####### ## ######## ## ##
 
#>


<#
.SYNOPSIS
Know if computer was booted using old legacy BIOS mode or new UEFI.
 
.DESCRIPTION
To make next boot efficient, we need to know in what mode the computer booted to this stage.
This function will tell us that.
If every tests fail, or if we can't determined the boot mode, it default to "BIOS" mode.
 
.EXAMPLE
$bootMode = Get-ComputerBootMode
 
.NOTES
General notes
#>

function Get-ComputerBootMode {
    [CmdletBinding()]
    [OutputType([String])]
    Param (
        # [Parameter(Mandatory = $true, ValueFromPipeLine = $true)][string]$string
    )
    Begin {
        Write-EnterFunction
    }

    Process {
        switch ($env:firmware_type) {
            'Legacy' {
                return "BIOS"
            }
            'UEFI' {
                return "UEFI"
            }
        }

        if ($null = Test-RegValueExist -RegPath 'HKLM:\System\CurrentControlSet\Control' -Name PEFirmwareType) {
            $value = Get-ItemPropertyValue 'HKLM:\System\CurrentControlSet\Control' -Name PEFirmwareType
            switch ($value) {
                1        { return "BIOS" }
                2        { return "UEFI" }
                default { return "BIOS" }
            }
        }

        return "BIOS"
    }

    End {
        Write-LeaveFunction
    }
}

<#
.SYNOPSIS
Configure computer to boot on user-asked partition
 
.DESCRIPTION
This function configure the boot flag on the correct partition
 
.PARAMETER Force
Force things
 
.PARAMETER Label
Label of the partition to configure
 
.PARAMETER MountPoint
Mountpoint of the target partition
 
.PARAMETER Disk
Disk device name of the partition
 
.PARAMETER PartNum
Partition number (can be several strings char since nvme disks. e.g. 'p1')
 
.PARAMETER Device
Full device adress like in '/dev/sda1'
 
.NOTES
General notes
#>

function Set-ComputerNextBootBIOS {
    [CmdletBinding()]
    [OutputType([Boolean])]
    Param (
        [switch]$Force,
        [Parameter(Mandatory = $true, ParameterSetName = 'LABEL')][string]$Label,
        [Alias('Letter', 'DriveLetter')]
        [Parameter(Mandatory = $true, ParameterSetName = 'MOUNTPOINT')][string]$MountPoint,
        [AllowNull]
        [Parameter(Mandatory = $false, ParameterSetName = 'DISKPART')][string]$Disk,
        [Parameter(Mandatory = $true, ParameterSetName = 'DISKPART')][string]$PartNum,
        [Parameter(Mandatory = $true, ParameterSetName = 'DEVICE')][string]$Device
        )
    Begin {
        Write-EnterFunction
    }

    Process {
        $diskNumber = -1
        $partNumber = -1
        switch ($PSCmdlet.ParameterSetName) {
            'LABEL' {
                $volume = Get-Volume -FileSystemLabel $Label
                $part = Get-Partition -Volume $volume
                $diskNumber = $part.DiskNumber
                $partNumber = $part.PartitionNumber
            }
            'MOUNTPOINT' {
                # we use $MountPoint[0] to get only the (1st) letter, stripping out the ':'
                $part = Get-Partition -DriveLetter $MountPoint[0]
                $diskNumber = $part.DiskNumber
                $partNumber = $part.PartitionNumber
            }
            'DISKPART' {
                $diskNumber = $Disk
                $partNumber = $PartNum
            }
            'Device' {
                eerror "-Device not supported on Windows."
            }
        }
        if ($diskNumber -lt 0) {
            eerror "Disk not found."
            return $false
        }
        if ($partNumber -lt 1) {
            eerror "Partition not found."
            return $false
        }

# $script = @"
# select disk ${diskNumber}
# select part ${partNumber}
# active
# "@
# $script | Out-File -FilePath "$TMP\nextboot.diskpart"
# Get-Content -Raw "$TMP\nextboot.diskpart" | ForEach-Object { edevel "$_" }
# $rc = Execute-Command -exe diskpart -args "/s $TMP\nextboot.diskpart"

        Set-Partition -DiskNumber $diskNumber -PartitionNumber $partNumber -IsActive $true

        return $rc
    }

    End {
        Write-LeaveFunction
    }
}

<#
.SYNOPSIS
Configure computer to boot on user-asked partition
 
.DESCRIPTION
This function configure UEFI to next-boot a specified device
 
.NOTES
General notes
#>

function Set-ComputerNextBootUEFI {
    [CmdletBinding()]
    [OutputType([Boolean])]
    Param (
        # [switch]$Force,
        # Label of an UEFI boot entry
        [Parameter(Mandatory = $false)][string]$UefiLabel = "Klonebot Boot Manager",
        # Label of a partition
        [Alias('Label', 'PartitionLabel')]
        [Parameter(Mandatory = $false, ParameterSetName = 'PARTLABEL')][string]$PartLabel,
        # MountPoint of a currently mounted volume or partition
        [Alias('Volume', 'Letter', 'DriveLetter')]
        [Parameter(Mandatory = $false, ParameterSetName = 'MOUNTPOINT')][string]$MountPoint,
        # disk device name
        [AllowNull]
        [Parameter(Mandatory = $false, ParameterSetName = 'DISKPART')][string]$Disk,
        # partition number
        [Parameter(Mandatory = $false, ParameterSetName = 'DISKPART')][string]$PartNum,
        # full device address
        [Parameter(Mandatory = $false, ParameterSetName = 'DEVICE')][string]$Device,
        # Boot PXE using IPv4 stack (only available with UEFI firmware)
        [Alias('PXE')]
        [Parameter(Mandatory = $false, ParameterSetName = 'NETWORK')][switch]$PXEv4,
        # Boot PXE using IPv6 stack (only available with UEFI firmware)
        [Parameter(Mandatory = $false, ParameterSetName = 'NETWORK')][switch]$PXEv6
        )
    Begin {
        Write-EnterFunction
    }

    Process {
        $entry = $null
        switch ($PSCmdlet.ParameterSetName) {
            'MOUNTPOINT' {
                $entry = Get-UEFIBootEntry -Key "osdevice" -Value "partition=$MountPoint"
            }
            'DISKPART' {
            }
            'Device' {
                $entry = Get-UEFIBootEntry -Key "device" -Value "$Device"
            }
            'NETWORK' {
                # try a set of values as manufacturer use their own
                if ($PXEv4) {
                    # Dell
                    if ([string]::IsNullOrEmpty($entry)) {
                        $entry = Get-UEFIBootEntry -UefiLabel "Onboard NIC(IPV4)"
                    }
                }
                if ($PXEv6) {
                    # Dell
                    if ([string]::IsNullOrEmpty($entry)) {
                        $entry = Get-UEFIBootEntry -UefiLabel "Onboard NIC(IPV6)"
                    }
                }
                # Dell
                if ([string]::IsNullOrEmpty($entry)) {
                    $entry = Get-UEFIBootEntry -UefiLabel "Onboard NIC"
                }
                # VMware
                if ([string]::IsNullOrEmpty($entry)) {
                    $entry = Get-UEFIBootEntry -UefiLabel "EFI Network"
                }
            }
        }

        if ([string]::IsNullOrEmpty($entry)) { return $false }
        $rc = Execute-Command -exe $Script:bcdedit -args "/bootsequence $($entry.id)"
        return $rc
    }

    End {
        Write-LeaveFunction
    }
}

<#
.SYNOPSIS
Get details of an UEFI boot entry
 
.DESCRIPTION
Return UEFI boot entry details as an object
 
.EXAMPLE
Get-UEFIBootEntry -UefiLabel "Windows Boot Manager"
 
.NOTES
General notes
#>

function Get-UEFIBootEntry {
    [CmdletBinding()]
    [OutputType([string])]
    Param (
        # Key name to search on
        [Parameter(Mandatory = $false, ParameterSetName = 'KEYVALUE')][string]$Key,
        # Value to find within key
        [Parameter(Mandatory = $false, ParameterSetName = 'KEYVALUE')][string]$Value,
        # Label of an UEFI boot entry
        [Parameter(Mandatory = $false, ParameterSetName = 'UEFILABEL')][string]$UefiLabel
    )
    Begin {
        Write-EnterFunction
    }

    Process {
        $bcd = Get-BCD -AsGUID

        switch ($PSCmdlet.ParameterSetName) {
            'UEFILABEL' {
                $id = ($bcd.keys | Where-Object { $bcd.$_.description -eq $UefiLabel })
                return $bcd.$id
            }
            'KEYVALUE' {
                $id = ($bcd.keys | Where-Object { $bcd.$_.$Key -eq $Value })
                return $bcd.$id
            }
            default {
                return $null
            }
        }
    }

    End {
        Write-LeaveFunction
    }
}

<#
 
 ######## ### ###### ## ## ###### ###### ## ## ######## ######## ## ## ## ######## ########
    ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
    ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
    ## ## ## ###### ##### ###### ## ######### ###### ## ## ## ## ## ###### ########
    ## ######### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
    ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
    ## ## ## ###### ## ## ###### ###### ## ## ######## ######## ####### ######## ######## ## ##
 
#>


<#
.SYNOPSIS
Create a new folder in the Operating System's task scheduler
 
.DESCRIPTION
Create a new folder in the Operating System's task scheduler daemon.
 
.PARAMETER FolderName
The name of the folder to create
 
.PARAMETER Root
An optional root folder to be the parent of the folder to create
 
.EXAMPLE
New-PwShFwScheduledTaskFolder -FolderName "MyDaemon"
 
.NOTES
On linux, this function just create an empty file under /etc/cron.d by default
#>

function New-PwShFwScheduledTaskFolder {
    [CmdletBinding()]
    [OutputType([Boolean])]
    [Alias('New-CronTaskFile')]
    Param (
        [Alias('Name')]
        [Parameter(Mandatory = $true, ValueFromPipeLine = $true)][string]$FolderName,
        [string]$Root = '\'
    )
    Begin {
        Write-EnterFunction
    }

    Process {
         $ErrorActionPreference = "stop"
        $scheduleObject = New-Object -ComObject schedule.service
        $scheduleObject.connect()
        $rootFolder = $scheduleObject.GetFolder($Root)
        Try {
           $null = $scheduleObject.GetFolder($FolderName)
        } Catch {
            $null = $rootFolder.CreateFolder($FolderName)
        } Finally {
            $ErrorActionPreference = "continue"
        }

        # test to return correct value
        Try {
            $null = $scheduleObject.GetFolder($FolderName)
            return $true
        } Catch {
            return $false
        }
    }

    End {
        Write-LeaveFunction
    }
}

<#
.SYNOPSIS
Create a new scheduled task / cron job
 
.DESCRIPTION
New-PwShFwScheduledTask function is a cross-platform wrapper for Scheduled Task / cron jobs.
It creates a full scheduled task / cron job within one command whatever the underlying OS is.
 
.PARAMETER Folder
Optional Folder name into which to create the task
 
.PARAMETER Name
Name of the task
 
.PARAMETER Command
Command or script to run
 
.PARAMETER Parameters
Arguments to pass to the command
 
.PARAMETER Description
Optional description of the task
 
.PARAMETER Username
Username to use to launch the task
 
.PARAMETER Minutes
Set the minutes number to trigger job (can be '*' to run every minutes).
Default = '*'
 
.PARAMETER Hour
Set the hour number to trigger job (can be '*' to run every hours).
Default = '*'
 
.PARAMETER DayOfMonth
Set the day of the month number to trigger job (can be '*' to run every days).
Default = '*'
 
.PARAMETER DayOWeek
Set the day of week number to trigger job (can be '*' to run every days of week).
Default = '*'
 
.PARAMETER Month
Set the month number to trigger job (can be '*' to run every months).
Default = '*'
 
.PARAMETER Year
Set the year number to trigger job (can be '*' to run every years).
Default = '*'
 
.PARAMETER EveryMinutes
Equals to -Minute '*'
 
.PARAMETER Hourly
Equals to -Minute 0 -Hours '*'
 
.PARAMETER Daily
Equals to -Minute 0 -Hours 0 -DayOfMonth '*'
 
.PARAMETER Weekly
Equals to -Minute 0 -Hours 0 -DayOfWeek 1 -Week '*'
 
.PARAMETER Monthly
Equals to -Minute 0 -Hours 0 -DayOfMonth 1 -Month '*'
 
.PARAMETER Yearly
Equals to -Minute 0 -Hours 0 -DayOfMonth 1 -Month 1 -Year '*'
 
.PARAMETER AtStartup
Trigger job on system startup
 
.PARAMETER AtLogon
Trigger job on session logon
 
.EXAMPLE
An example
 
.NOTES
General notes
#>

function New-PwShFwScheduledTask {
    [CmdletBinding(DefaultParameterSetName = 'EXACT_TRIGGER')]
    [OutputType([String])]
    Param (
        [string]$Folder = "\",
        [Parameter(Mandatory = $true, ValueFromPipeLine = $true)][string]$Name,
        [Parameter(Mandatory = $true, ValueFromPipeLine = $true)][string]$Command,
        [Parameter(Mandatory = $false, ValueFromPipeLine = $true)][string]$Parameters,
        [string]$Description = "",
        [string]$Username = $env:USERNAME,
        [Parameter(ParameterSetName = 'EXACT_TRIGGER')][string]$Minute = '*',
        [Parameter(ParameterSetName = 'EXACT_TRIGGER')][string]$Hour = '*',
        [Parameter(ParameterSetName = 'EXACT_TRIGGER')][string]$DayOfMonth = '*',
        [Parameter(ParameterSetName = 'EXACT_TRIGGER')][string]$DayOfWeek = '*',
        # [Parameter(ParameterSetName = 'EXACT_TRIGGER')][string]$Week = '*',
        [Parameter(ParameterSetName = 'EXACT_TRIGGER')][string]$Month = '*',
        [Parameter(ParameterSetName = 'EXACT_TRIGGER')][string]$Year = '*',
        [Parameter(ParameterSetName = 'ALIAS_TRIGGER')][switch]$EveryMinutes,
        [Parameter(ParameterSetName = 'ALIAS_TRIGGER')][switch]$Hourly,
        [Parameter(ParameterSetName = 'ALIAS_TRIGGER')][switch]$Daily,
        [Parameter(ParameterSetName = 'ALIAS_TRIGGER')][switch]$Weekly,
        [Parameter(ParameterSetName = 'ALIAS_TRIGGER')][switch]$Monthly,
        [Parameter(ParameterSetName = 'ALIAS_TRIGGER')][switch]$Yearly,
        [Parameter(ParameterSetName = 'ALIAS_TRIGGER')][switch]$AtStartup,
        [Parameter(ParameterSetName = 'ALIAS_TRIGGER')][switch]$AtLogon
    )
    Begin {
        Write-EnterFunction
    }

    Process {
        if ([string]::IsNullOrEmpty($Description)) { $Description = "$Name - $Command $Parameters" }
        $action = New-ScheduledTaskAction -Execute $Command -Argument $Parameters
        switch ($PSCmdlet.ParameterSetName) {
            'EXACT_TRIGGER' {
            }
            'ALIAS_TRIGGER' {
                if ($EveryMinutes)    { $trigger = New-ScheduledTaskTrigger -Once -At 0am -RepetitionInterval (New-TimeSpan -Seconds 60) -RepetitionDuration ([System.TimeSpan]::MaxValue) }
                if ($Hourly)        { $trigger = New-ScheduledTaskTrigger -Once -At 0am -RepetitionInterval (New-TimeSpan -Minutes 60) -RepetitionDuration ([System.TimeSpan]::MaxValue) }
                if ($Daily)            { $trigger = New-ScheduledTaskTrigger -Daily -At 0am }
                if ($Weekly)        { $trigger = New-ScheduledTaskTrigger -Weekly -DaysOfWeek $DayOfWeek -At 0am }
                if ($Monthly)        { $trigger = New-ScheduledTaskTrigger -Daily -DaysInterval 30 -At 0am }
                if ($Yearly)        { $trigger = New-ScheduledTaskTrigger -Daily -DaysInterval 365 -At 0am }
                if ($AtStartup)        { $trigger = New-ScheduledTaskTrigger -AtStartup }
                if ($AtLogon)        { $trigger = New-ScheduledTaskTrigger -AtLogon }
            }
        }
        try {
            $task = Register-ScheduledTask -TaskPath $Folder -TaskName $Name -User $Username -Description $Description -Action $action -Trigger $trigger
            $rc = $?
        } catch {
            eerror $_
            $rc = $false
        }
        return $rc
    }

    End {
        Write-LeaveFunction
    }
}

<#
 
 ######## ######## ###### #### ###### ######## ######## ## ##
 ## ## ## ## ## ## ## ## ## ## ## ## ##
 ## ## ## ## ## ## ## ## ## ####
 ######## ###### ## #### ## ###### ## ######## ##
 ## ## ## ## ## ## ## ## ## ## ##
 ## ## ## ## ## ## ## ## ## ## ## ##
 ## ## ######## ###### #### ###### ## ## ## ##
 
#>


# @var RegistryLoaded
# @brief Hashtable to remember what is loaded where
# @description Each time an offline registry file is loaded into current registry, record this in the hashtable.
# The format is { "/full/path/to/filename" : "HKLM:\path\to\hive" }
$RegistryLoaded = @{}

<#
.SYNOPSIS
Load list of current offline registry loaded into live registry
 
.DESCRIPTION
The list is a hashtable saved at "HKLM:\Software\PwSh.Fw\pwsh.fw.os" folder into "RegistryLoaded" property
 
.NOTES
It is an internal function. Do not use.
#>


function Load-OfflineWindowsRegistryMountPoint {
    [CmdletBinding()]
    [OutputType([hashtable])]
    Param (
        # [Parameter(Mandatory = $true, ValueFromPipeLine = $true)][string]$string
    )
    Begin {
        Write-EnterFunction
    }

    Process {
        [hashtable]$RegistryLoaded = @{}
        if (Test-RegKeyExist "HKLM:\Software\PwSh.Fw\pwsh.fw.os\RegistryLoaded") {
            $keys = Get-Item "HKLM:\Software\PwSh.Fw\pwsh.fw.os\RegistryLoaded" | Select-Object -ExpandProperty property
            foreach ($k in $keys) {
                $kUnescaped = [regex]::unescape($k)
                $RegistryLoaded.$kUnescaped = Get-ItemPropertyValue -Path "HKLM:\Software\PwSh.Fw\pwsh.fw.os\RegistryLoaded" -Name $k
            }
        }
        return $RegistryLoaded
    }

    End {
        Write-LeaveFunction
    }
}

<#
.SYNOPSIS
Save list of current offline registry loaded into live registry
 
.DESCRIPTION
The list is a hashtable saved at "HKLM:\Software\PwSh.Fw\pwsh.fw.os" folder into "RegistryLoaded" property
 
.NOTES
It is an internal function. Do not use.
#>

function Save-NewOfflineWindowsRegistryMountPoint {
    [CmdletBinding()]
    [OutputType([void])]
    Param (
        [Parameter(Mandatory = $true, ValueFromPipeLine = $true)][string]$Filename,
        [Parameter(Mandatory = $true, ValueFromPipeLine = $true)][string]$MountPoint
    )
    Begin {
        Write-EnterFunction
    }

    Process {
        try {
            [hashtable]$RegistryLoaded = Load-OfflineWindowsRegistryMountPoint
        } catch {
            [hashtable]$RegistryLoaded = @{}
        }
        $Filename = [regex]::Escape($Filename)
        # $RegistryLoaded.$Filename = [regex]::Escape($MountPoint)
        $null = New-Item -Path "HKLM:\Software\PwSh.Fw\pwsh.fw.os\RegistryLoaded" -ItemType directory -ErrorAction SilentlyContinue
        $null = New-ItemProperty -Path "HKLM:\Software\PwSh.Fw\pwsh.fw.os\RegistryLoaded" -Name $Filename -Value $MountPoint -Force
    }

    End {
        Write-LeaveFunction
    }
}

function Save-RemoveOfflineWindowsRegistryMountPoint {
    [CmdletBinding()]
    [OutputType([void])]
    Param (
        [Parameter(Mandatory = $true, ValueFromPipeLine = $true, ParameterSetName = 'FILENAME')][string]$Filename,
        [Parameter(Mandatory = $true, ValueFromPipeLine = $true, ParameterSetName = 'MountPoint')][string]$MountPoint
    )
    Begin {
        Write-EnterFunction
    }

    Process {
        try {
            [hashtable]$RegistryLoaded = Load-OfflineWindowsRegistryMountPoint
        } catch {
            [hashtable]$RegistryLoaded = @{}
        }
        switch ($PSCmdlet.ParameterSetName) {
            'FILENAME' {
                $key = [regex]::Escape($Filename)
            }
            'MountPoint' {
                $key = $RegistryLoaded.keys | Where-Object { $RegistryLoaded.$_ -eq $MountPoint }
                $key = [regex]::Escape($key)
            }
        }
        Remove-ItemProperty -Path "HKLM:\Software\PwSh.Fw\pwsh.fw.os\RegistryLoaded" -Name $key -Force
    }

    End {
        Write-LeaveFunction
    }
}

<#
.SYNOPSIS
Mount a windows registry file
 
.DESCRIPTION
Mount a windows registry file like user.dat, SYSTEM or SOFTWARE from offline windows disk, or even BCD file.
By default, content of this registry is mounted under HKLM:\{Generated GUID} registry key.
 
.PARAMETER File
Full path to a windows registry file. Must be used alone.
 
.PARAMETER Path
Full path to an offline windows installation folder. Must be used with -Hive parameter.
 
.PARAMETER Hive
Name of a windows hive. Currently, only SOFTWARE and SYSTEM are supported. Must be used with -Path parameter
 
.PARAMETER MountPoint
Override default HKLM:\$GUID MountPoint by explicitly specifying MountPoint. Must be full registry path e.g. "HKLM:\Some_Path"
 
.EXAMPLE
Mount-OfflineWindowsRegistry -Path E:\Windows -Hive SOFTWARE
This example will mount HKLM\SOFTWARE registry hive from an offline windows disk connected as E:
 
.EXAMPLE
Mount-OfflineWindowsRegistry -File E:\Users\<username>\user.dat
This example will mount a user profile from the same offline windows disk
 
.OUTPUTS
Registry path to where the registry file is mounted
 
.NOTES
General notes
#>


function Mount-OfflineWindowsRegistry {
    [CmdletBinding(
        DefaultParameterSetName="HIVE"
    )]Param(
        # Parameter help description
        [Parameter(ParameterSetName="FILENAME",ValueFromPipeLine = $true)]
        [ValidateScript({
            if(-Not ($_ | Test-Path) ){
                throw "File not found."
            }
            if(-Not ($_ | Test-Path -PathType Leaf) ){
                throw "The File argument must be a filename."
            }
            return $true
        })][System.IO.FileInfo]$File = "X:\Windows\System32\config\SOFTWARE",

        [Parameter(ParameterSetName="HIVE",ValueFromPipeLine = $true)]
        [ValidateScript({
            if(-Not ($_ | Test-Path) ){
                throw "File or folder does not exist"
            }
            if(-Not ($_ | Test-Path -PathType Container) ){
                throw "The Path argument must be a Folder."
            }
            return $true
        })][System.IO.DirectoryInfo]$Path = "X:\Windows",

        [Parameter(ParameterSetName="HIVE")]
        [ValidateSet('SOFTWARE','SYSTEM')]
        [string]$Hive = "SOFTWARE",

        [string]$MountPoint
    )
    Begin {
        Write-EnterFunction
        $RegistryLoaded = Load-OfflineWindowsRegistryMountPoint
    }

    Process {
        switch ($PSCmdlet.ParameterSetName) {
            "FILENAME" {
                $Hive = $File.BaseName
                $filename = $File.FullName
            }
            "HIVE" {
                $filename = $Path.FullName + "\System32\config\" + $Hive
            }
        }

        # return registered MountPoint if file is already loaded
        if ($null -ne $RegistryLoaded.$filename) {
            $MountPoint = $RegistryLoaded.$filename
            if (Test-RegKeyExist -RegPath $MountPoint) {
                return $MountPoint
            } else {
                Write-Warning "Registry already loaded but MountPoint not found. Try to reload."
            }
        }
        if ([string]::IsNullOrEmpty($MountPoint)) {
            $MountPoint = "HKLM:\$(New-Guid)"
        }
        if (fileExist -Name $filename) {
            try {
                $rc = Execute-Command reg load $MountPoint.Replace(':', '') $filename
            } catch {
                Write-Error $_
            }
            if (Test-RegKeyExist -RegPath $MountPoint) {
                $null = Save-NewOfflineWindowsRegistryMountPoint -File $filename -MountPoint $MountPoint
            }
        } else {
            Write-Error "Cannot find registry hive at $($Path.FullName)"
        }

        return $MountPoint
    }

    End {
        Write-LeaveFunction
    }
}

<#
    .SYNOPSIS
    Unmount a windows registry file
 
    .DESCRIPTION
    Umount a windows registry file previously mounted with Mount-OfflineWindowsRegistry.
 
    .EXAMPLE
    New-TemplateFunction -string "a string"
 
#>

function DisMount-OfflineWindowsRegistry {
    [CmdletBinding(
        DefaultParameterSetName = "HIVE"
    )]Param (
        # MountPoint is a registry path where the file is mounted
        [Alias('RegPath')]
        [Parameter(ParameterSetName="HIVE",ValueFromPipeLine = $true)]
        [string]$MountPoint,

        # Full path and filename to the mounted file
        [Parameter(ParameterSetName="FILE",ValueFromPipeLine = $true)]
        [string]$File,

        # Dismount all files mounted
        [Parameter(ParameterSetName="All",ValueFromPipeLine = $true)]
        [switch]$All
    )
    Begin {
        Write-EnterFunction
        $RegistryLoaded = Load-OfflineWindowsRegistryMountPoint
    }

    Process {
        switch ($PSCmdlet.ParameterSetName) {
            "FILENAME" {
                [array]$MountPoints = @($RegistryLoaded.$File)
            }
            "HIVE" {
                [array]$MountPoints = @($MountPoint)
            }
            "All" {
                [array]$MountPoints = $RegistryLoaded.Values
            }
        }
        if ($MountPoints.count -eq 0) {
            Write-Error "No offline registry found."
            return [void]
        }
        $MountPoints | ForEach-Object {
            # Write-Devel "_ = $_"
            $mp = $_
            # Write-Devel "mp = $mp"
            $DosRegPath = $mp.Replace(':', '')
            $rc = Execute-Command reg unload $DosRegPath
            if (Test-RegKeyExist -RegPath $mp) {
                Write-Error "Unable to unload registry key at '$mp'."
            } else {
                Save-RemoveOfflineWindowsRegistryMountPoint -MountPoint $mp
            }
        }
    }

    End {
        Write-LeaveFunction
    }
}

<#
.SYNOPSIS
Get files loaded in the registry
 
.DESCRIPTION
Return the list of files currently loaded in the registry.
Only files loaded with Mount-OfflineWindowsRegistry can be listed
 
.EXAMPLE
Get-OfflineWindowsRegistry
 
.NOTES
General notes
#>

function Get-OfflineWindowsRegistry {
    [CmdletBinding()]
    [OutputType([String])]
    Param (
        [Parameter(ParameterSetName="HIVE",ValueFromPipeLine = $true)]
        [string]$RegPath,
        [Parameter(ParameterSetName="FILE",ValueFromPipeLine = $true)]
        [string]$File,
        [Parameter(ParameterSetName="All",ValueFromPipeLine = $true)]
        [switch]$All
    )
    Begin {
        Write-EnterFunction
    }

    Process {
        switch ($PSCmdlet.ParameterSetName) {
            "FILENAME" {
                return $RegistryLoaded.$File
            }
            "HIVE" {
                return $RegistryLoaded.Keys | Where-Object { $RegistryLoaded[$_] -eq $RegPath }
            }
            "All" {
                return $RegistryLoaded
            }
        }
    }

    End {
        Write-LeaveFunction
    }
}