Im trying to get remote registry key vaules using this script, it works fine but throws a few null errors on certain units, I'd like it to just output the error text if it can't find powershell 5.1 key.
*clients are win 7 HP, Workgroup *I know my logic is off (red if it's there, green if not) just trying to see what I can come up with myself before asking you guys for assistance
$ComputerName = get-content "C:\Users\David\Desktop\IPS.txt"
$Hive = 'LocalMachine'
$KeyPath = 'SOFTWARE\Microsoft\PowerShell\1\PowerShellEngine'
$Value = 'PowerShellVersion'
$KeyPath1 = 'SOFTWARE\Microsoft\PowerShell\3\PowerShellEngine'
$Value1 = 'PowerShellVersion'
Foreach ($Computer in $ComputerName) {
if (Test-Connection $computer -Count 2 -Quiet) {
$reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($Hive, $Computer)
$key = $reg.OpenSubKey("$KeyPath")
$Data = $key.GetValue($Value)
$reg1 = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($Hive, $Computer)
$key1 = $reg1.OpenSubKey("$KeyPath1")
$Data1 = $key1.GetValue($Value1)
If (($data = "2.0") -and ($Data1 = "5.1.14409.1005")){
Write-Host "$Computer needs updated " -ForegroundColor Red
##Added to try and do some error checking [string]::IsNullOrEmpty($Data1)
##Added to try and do some error checking Write-Host $Data1
}else {
Write-Host ""
Write-Host "$Computer $Data" -ForegroundColor Green
Write-Host "$Computer $Data1" -ForegroundColor Green
Write-Host ""
}
}
}
Error I'm getting:
CodePudding user response:
The error is occurring on line 18, which is:
$Data1 = $key1.GetValue($Value1)
Since the error indicates you are calling a method on a null-valued expression, that shows that the error has occurred because $key1
is null.
$key1
, in turn, is expected to have a value after the previous line (17) is executed:
$key1 = $reg1.OpenSubKey("$KeyPath1")
OpenSubKey returns null when the operation failed. This would happen if the subkey did not exist. So your program needs to check whether $key1
is null after line 17. Then, instead of attempting to call a method on a null object, your program can put out an error message saying that the subkey could not be opened.
CodePudding user response:
If (($data = "2.0") -and ($Data1 = "5.1.14409.1005")){
The above is always true as you are doing assignments (=) vs testing (-eq).
Code should read:
If (($data -eq "2.0") -and ($Data1 -eq "5.1.14409.1005")){