Dictionaries/Dict.Windows/Dict.Windows.psm1

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


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


<#
.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.
 
    .PARAMETER $string
    a string
 
    .EXAMPLE
    New-TemplateFunction -string "a string"
 
#>

function DisMount-OfflineWindowsRegistry {
    [CmdletBinding(
        DefaultParameterSetName = "HIVE"
    )]Param (
        [Parameter(ParameterSetName="HIVE",ValueFromPipeLine = $true)]
        [string]$MountPoint,
        [Parameter(ParameterSetName="FILE",ValueFromPipeLine = $true)]
        [string]$File,
        [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
    }
}