Extract registry value from multiple computers using powershell

24,458

You'll need to catch exceptions with a try/catch.

$strMachineName = import-csv .\computer_name.csv
foreach ($line in $strMachineName)
{
    try {
        $reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $line.computer)
        $regkey = $reg.OpenSubkey("SOFTWARE\\Olympus\\DSSPlayerPro\\Transcription Module\\UserInformation")
        $serialkey = $regkey.GetValue("SerialNumber")

        ('"{0}","{1}"' -f $line.computer, $serialkey) | out-file C:\stdout.csv -append -encoding ascii
    } catch {
        ('"{0}","{1}"' -f $line.computer, $_) | out-file C:\stderr.csv -append -encoding ascii
    }
}

This creates two files (stdout.csv and stderr.csv). Successful queries are stored in stdout.csv and failed queries are stored in stderr.csv.

Share:
24,458
smierdziel
Author by

smierdziel

Updated on October 18, 2020

Comments

  • smierdziel
    smierdziel over 3 years

    A colleague and I are attempting to create a powershell script which uses a CSV file that contains the names of all our computers on the company network and uses those names to connect to a remote registry and extract a specific value.

    This is what we have so far:

    $strMachineName = import-csv .\computer_name.csv
    foreach ($line in $strMachineName)
    {
                    $reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $line.computer)
                    $regkey = $reg.OpenSubkey("SOFTWARE\\Olympus\\DSSPlayerPro\\Transcription Module\\UserInformation")
                    $serialkey = $regkey.GetValue("SerialNumber")
                    write-host $line","$serialkey
    }
    

    Now, this script works fine but there are output issues that make it hard to understand with many computers.

    We would like to be able to output stdout to another file, either a csv or txt, and we would also like to be able to output stderr to null, or a seperate file so we can inspect it later.

    My research has made me believe that write-host is not the appropriate command to be using since it cannot output to a file when variables are used (??), so I tried to use echo but I'm having problems getting variables to work as I would like.

    I appreciate any help, thank you!