Functions/registry.ps1


function Set-RegistryValue(
    [Parameter(Mandatory = $true, Position = 0)]
    [ValidateNotNullOrEmpty()]
    [string]$regKeyPath,

    [Parameter(Mandatory = $true, Position = 1)]
    [ValidateNotNullOrEmpty()]
    [string]$regValueName,

    [Parameter(Mandatory = $true, Position = 2)]
    [ValidateNotNullOrEmpty()]
    [string]$regValue,

    [Parameter(Position = 3)]
    [string] $registryName = "Registry"
) {
    $result = Get-RegistryValue $regKeyPath $regValueName
    if ($result -eq $null) {
        Write-Host "${registryName}: Creating Key '${regValueName}' value '${regValue}'"
        Set-ItemProperty -Path $regKeyPath -Name ${regValueName} -Value $regValue
    }
    else {
        Write-Host "${registryName}: Key '${regValueName}' already exists with value '${result}'"
    }
}

# Gets the specified registry value or $null if it is missing
function Get-RegistryValue(
    [Parameter(Mandatory = $true, Position = 0)]
    [ValidateNotNullOrEmpty()]
    [string] $path,
    
    [Parameter(Mandatory = $true, Position = 1)]
    [ValidateNotNullOrEmpty()]
    [string] $name) {
    $key = Get-Item -LiteralPath $path -ErrorAction SilentlyContinue
    if ($key) {
        $key.GetValue($name, $null)
    }
}

$envCurrentUserPath = "HKCU:\Environment"
$envLocalMachinePath = "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
function Set-EnvironmentVar(
    [Parameter(Mandatory = $true, Position = 0)]
    [ValidateNotNullOrEmpty()]
    [string]$name,

    [Parameter(Mandatory = $true, Position = 1)]
    [ValidateNotNullOrEmpty()]
    [string]$regValue,

    [Parameter(Position = 2)]
    [ValidateSet("user", "machine")]
    [string]
    # environment variable type: user, or machine. Default is 'user'
    $variableType = 'user'
) {
    $environmentPath = $envCurrentUserPath
    if ($variableType -ceq 'machine') {
        $environmentPath = $envLocalMachinePath
    }
    Set-RegistryValue $environmentPath $name $regValue "Environment Variable"
}

function Get-EnvironmentVar(
    [Parameter(Mandatory = $true)]
    [ValidateNotNullOrEmpty()]
    [string] $name,

    [ValidateSet("user", "machine")]
    [string]
    # environment variable type: user, or machine. Default is 'user'
    $variableType = 'user'
) {
    $environmentPath = $envCurrentUserPath
    if ($variableType -ceq 'machine') {
        $environmentPath = $envLocalMachinePath
    }
    return Get-RegistryValue $environmentPath $name
}

function Set-LocalMachineRunOnceVar(
    [Parameter(Mandatory = $true, Position = 0)]
    [ValidateNotNullOrEmpty()]
    [string]$name,

    [Parameter(Mandatory = $true, Position = 1)]
    [ValidateNotNullOrEmpty()]
    [string]$regValue
) {
    $localMachineRunOncePath = "HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce"
    Set-RegistryValue $localMachineRunOncePath $name $regValue "LocalMachine: RunOnce Variable"
}