ninja-one/manage-registry-key.ps1

#Requires -Version 5.1

<#
.SYNOPSIS
    Modifies or deletes a registry key
#>


[CmdletBinding()]
param (
    [string]$KeyPath,
    [ValidateSet('String', 'DWord', 'QWord', 'Binary', 'MultiString', 'ExpandString')]
    [string]$Type,
    [string]$Name,
    [string]$Value,
    [switch]$Delete = [System.Convert]::ToBoolean($env:deleteRegKey)
)

begin {
      
    if (-not $KeyPath) {
        if ($env:keyPath -and $env:keyPath -notlike "null") {
            $KeyPath = $env:keyPath
        }
        else {
            Write-Host "[ERROR] Please specify a registry path."
            exit 1
        }
    }

    if (-not $Name) {
        if ($env:name -and $env:name -notlike "null") {
            $Name = $env:name
        }
        else {
            Write-Host "[ERROR] Please specify a registry key name."
            exit 1
        }
    }
    
    if (-not $Type -and -not $Delete) {
        if ($env:type -and $env:type -notlike "null") {
            $Type = $env:type
        }
    }

    if (-not $Value -and -not $Delete) {
        if ($env:value -and $env:value -notlike "null") {
            $Value = $env:value
        }
        else {
            Write-Host "[ERROR] Please specify a registry key value."
            exit 1
        }
    }
}
process {
    try {
        if ($Delete) {
            # Delete the registry key value
            if (Test-Path "Registry::$KeyPath") {
                Remove-ItemProperty -Path "Registry::$KeyPath" -Name $Name -ErrorAction Stop
                Write-Host "[INFO] Successfully deleted registry key value: $KeyPath\$Name"
            }
            else {
                Write-Host "[ERROR] Registry path does not exist: $KeyPath"
                exit 1
            }
        }
        else {
            # Ensure the registry path exists
            if (-not (Test-Path "Registry::$KeyPath")) {
                New-Item -Path "Registry::$KeyPath" -Force -ErrorAction Stop
                Write-Host "[INFO] Created registry path: $KeyPath"
            }

            # Set or update the registry key value
            Set-ItemProperty -Path "Registry::$KeyPath" -Name $Name -Value $Value -Type $Type -ErrorAction Stop
            Write-Host "[INFO] Successfully set registry key: $KeyPath\$Name = $Value"
        }
    }
    catch {
        Write-Host "[ERROR] Failed to add or remove the following registry key: $KeyPath\$Name"
        Write-Error $_
        Write-Host "[ERROR] occurred at line number: $($_.InvocationInfo.ScriptLineNumber)"
        exit 1
    }
    exit 0
}
end {

}