Thursday, December 12, 2019

Reading registry values in powershell without an error red lettering


Surprisingly there wasn't a complete answer for this when searching the web after a coworker asked me for help with this. I found some examples but they still would red letter when the key wasn't present and that's not something you want an end user to see and be confused about. There's obviously a difference between the script having a failure error and not being able to find a registry key value because it happens to not be present or they have a different version of Office for example, so maybe the 15.0 key is present, but the 16.0 is not.

The below should remove the red lettering and allow you to enumerate through the key values if they are present and the path is present. Enjoy.



 
Function Get-RegistryKeyPropertiesAndValues
{
    Param(
    [Parameter(Mandatory=$true)]
    [string]$path)

    if (test-path $path)
    {
        Set-Location -Path $path
        Get-Item . |

        Select-Object -ExpandProperty property |
        ForEach-Object {
            New-Object psobject -Property @{“property”=$_;
            “Value” = (Get-ItemProperty -Path . -Name $_).$_}
        }
    }
    else
    {
        return "path doesn't exist";
    }
}

cls;

$path = "HKCU:\Software\Microsoft\Office\16.0\Outlook\AutoDiscover";
#$path = "HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell";
$valz = Get-RegistryKeyPropertiesAndValues -path $path;

if ($valz -ne "path doesn't exist")
{
    foreach ($val in $valz)
    {
        Write-Host "property: " $val.property;
        Write-Host "value: " $val.Value;
    }
}
else
{
    $valz;
}