Thursday, July 31, 2014

Powershell: Discover if a registry key exists

This code is only one example and is targeted at the HKEY_CLASSES_ROOT:

param
(
   [Parameter(Mandatory=$True)]
   [string]$Subkey
)
function Test-Registry-key
{
    param
    (
        [Parameter(Mandatory=$True)]
        [Microsoft.Win32.RegistryKey]$Regkey,
        [Parameter(Mandatory=$True)]
        [string]$key
    )
    $rkey = $regkey.OpenSubKey($key)
    if(!($rkey))
    {
        return "Key does not exist."
    }
    else
    {
        return "Key exists."
    }

}
$regkey = [Microsoft.Win32.Registry]::ClassesRoot
$ret = Test-Registry-Key $regkey $Subkey
write-host $ret

No comments:

Post a Comment