Thursday, March 15, 2007

Powershell: Return value from remote registry key

One of the first things I wanted to do in Powershell was to get a value from a registry key on remote servers and show it to me in a list. For example, we use a backup program called Tivoli Storage Manager. If I want to see what version of the TSM client I have installed on all of my managed servers, here is a script that will do it.

A few things to note about this script. I'm using another function to get the list of servers that I want to check (see my previous blog post for more information). This script will actually ping each server before running get-wmiobject because get-wmiobject has a long timeout, and I dont want to have to wait 60 seconds for every server that may not be on the network.


$ErrorActionPreference = "silentlycontinue"
$starttime = get-date
$HKLM = 2147483650

$servers = get-servers

$auth = get-credential admin

# display the header info
write-host $('{0,-17}{1}' -f "ServerName","TSM Version")
write-host "--------------- -----------"

$count = 0

# sort the computer names and get various wmi info for that server
$servers.keys | sort | foreach `
{
$ping = get-wmiobject win32_pingstatus -filter "address='$_'"

if ($ping.statuscode -eq 0)
{
if ($servers.$_ -eq "ad" )
{
$reg = get-wmiobject -list -namespace root\default -computer $_ | where-object {$_.name -eq "StdRegProv" }

if ($? -eq $false)
{
write-host $_.tolower() "...wmi query failed." -foregroundcolor Red
}
else
{
$tsmver = $reg.getstringvalue($HKLM, "software\ibm\adsm\currentversion\backupclient","ptflevel")

write-host $('{0,-17}{1}' -f $_.tolower(),$tsmver.svalue)
}
}
else
{
$reg = get-wmiobject -list -namespace root\default -computer $_ -credential $auth

if ($? -eq $false)
{
write-host $_.tolower() "...wmi query failed." -foregroundcolor Red
}
else
{
$tsmver = $reg.getstringvalue($HKLM, "software\ibm\adsm\currentversion\backupclient","ptflevel")

write-host $('{0,-17}{1}' -f $_.tolower(),$tsmver.svalue)
}
}
}
else
{
write-host $_.tolower() "...ping failed." -foregroundcolor Red
}

$count += 1
}

write-host
write-host "Total servers: $count"
$endtime = (get-date).subtract($starttime)
write-host "Elapsed time:" $('{0:D2}:{1:D2}:{2:D2}' -f $endtime.hours,$endtime.minutes,$endtime.seconds)
write-host

No comments: