Untitled

 avatar
unknown
plain_text
a year ago
2.5 kB
23
Indexable
# Utility Function: Registry.ShouldBeKey
## This function is used to ensure that a registry key exists and its (Default) value is set to a specific value.
function Registry.ShouldBeKey {
    [CmdletBinding()]
    param(
        # The registry path to the key.
        [Parameter(Mandatory)]
        [String]$Path,
        # The name of the registry key.
        [Parameter(Mandatory)]
        [String]$Name,
        # The value to set the (Default) value to.
        [Parameter(Mandatory)]
        [Object]$Value,
        # Don't confirm that the registry key was set correctly.
        [Switch]$SkipConfirmation
    )
    begin {
        # Make sure the registry path exists.
        if (!(Test-Path $Path)) {
            Write-Warning ("Registry path '$Path' does not exist. Creating.")
            New-Item -Path $Path -Force | Out-Null
        }
        # Make sure it's actually a registry path.
        if (!(Get-Item $Path).PSProvider.Name -eq 'Registry' -and !(Get-Item $Path).PSIsContainer) {
            throw "Path '$Path' is not a registry path."
        }
        $LoopCount = 0
    }
    process {
        do {
            # Make sure the registry key exists.
            if (!(Test-Path "$Path\$Name")) {
                Write-Warning ("Registry key '$Name' in path '$Path' does not exist. Creating.")
                New-Item -Path "$Path\$Name" -Force | Out-Null
            }
            # Set the (Default) value of the registry key.
            Set-ItemProperty -Path "$Path\$Name" -Name '(Default)' -Value $Value
            # Make sure the (Default) value is correct.
            if (!$SkipConfirmation) {
                if ((Get-ItemProperty -Path "$Path\$Name" -Name '(Default)').'(Default)' -ne $Value) {
                    Write-Warning ("Registry key '$Name' in path '$Path' (Default) value is not correct. Setting to '$Value'.")
                    Set-ItemProperty -Path "$Path\$Name" -Name '(Default)' -Value $Value
                }
                $LoopCount++
            } else {
                # Short circuit the loop if we're skipping confirmation.
                $LoopCount = 3
            }
        } while ((Get-ItemProperty -Path "$Path\$Name" -Name '(Default)').'(Default)' -ne $Value -and $LoopCount -lt 3)
    }
}
$RegPath = 'HKLM:\SYSTEM\CurrentControlSet\Control\SafeBoot\Network'
Registry.ShouldBeKey -Path $RegPath -Name 'NinjaRMMAgent' -Value 'Service'
Registry.ShouldBeKey -Path $RegPath -Name 'ncstreamer' -Value 'Service'
Editor is loading...
Leave a Comment