Public/Update-pseRegistryValueData.ps1

Function Update-pseRegistryValueData {
    <#
    .SYNOPSIS
    This function replaces or creates a registry key with the specified path, value name, data, and value type.
 
    .DESCRIPTION
    This is a helper function that replaces or creates a registry key with the specified path, value name, data, and value type.
 
    .PARAMETER KeyPath
    Specifies the registry path where the key should be located or created.
 
    .PARAMETER ValueName
    Specifies the name of the registry value to be updated or created.
 
    .PARAMETER ValueData
    Specifies the data to be set for the registry value.
 
    .PARAMETER ValueType
    Specifies the data type of the registry value. Valid values are 'String' and 'DWord'.
 
    .EXAMPLE
    Update-pseRegistryValueData -KeyPath "HKLM:\Software\Example" -ValueName "SampleValue" -ValueData "TestData" -ValueType "String"
    Updates or creates a registry key "SampleValue" with data "TestData" of type String under the path "HKLM:\Software\Example".
 
    .EXAMPLE
    Update-pseRegistryValueData -KeyPath "HKLM:\Software\Example" -ValueName "SampleValue" -ValueData 123 -ValueType "DWord"
    Updates or creates a registry key "SampleValue" with data 123 of type DWord under the path "HKLM:\Software\Example".
 
    .NOTES
    Author : owen.heaume
    Version : 1.0.0 - Initial release
    #>

    [cmdletbinding()]

    param (
        [Parameter (mandatory = $true)]
        [string]$KeyPath,

        [Parameter (mandatory = $true)]
        [string]$ValueName,

        [Parameter (mandatory = $true)]
        [string]$ValueData,

        [Parameter (mandatory = $true)]
        [ValidateSet('String', 'DWord')]
        [string]$ValueType
    )

    # If any part of the reg path doesn't exist at all, this will create it (New-pse...), if the value name already exists, it just updates (Set-pse...)
    try {
        Write-Host "Attempting to update the registry key '$KeyPath\$ValueName\$ValueData\$ValueType'" -ForegroundColor DarkGray
        if (Get-ItemProperty -Path $KeyPath -Name $ValueName -ErrorAction SilentlyContinue) {
            $null = Set-pseRegistryValueName -KeyPath $KeyPath -ValueName $ValueName -ValueType $ValueType -ValueData $ValueData
            Write-Host "Successfully updated the registry key" -ForegroundColor DarkGreen
        } else {
            $null = New-pseRegistryKey -KeyPath $keypath -ValueName $ValueName -ValueType $ValueType -ValueData $ValueData
            Write-Host "Successfully created the registry key" -ForegroundColor DarkGreen
        }
    } catch {
        Write-Error "Unable to update the registry key"
    }
}