Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
974 views
in Technique[技术] by (71.8m points)

windows - Checking if registry value is equal to 1 is not working correctly

I have slopped together bits of PowerShell to remote query a list of machines, stored in a .csv file, for a registry value. If the registry key's value is equal to '1', the script should then create a text file using the machine's name as the name of the text file.

Everything works great. The script runs happily without any errors. The problem is that when I go back and remotely check a targeted registry value, I find that the value isn't 1. The script is simply creating a file for every line in the .csv.

What am I doing wrong?

EDIT*** I found a problem I had a typo in the $key variable for the registry path. 7/17/2013 2:21p

$File = Import-Csv 'c:empmachines.csv'

foreach ($line in $file)
{
  $machinename = $line.machinename
  trap [Exception] {continue}
  $reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey("LocalMachine",$MachineName)
  $key = "SOFTWARE\Microsoft\Windows NT\CurrentVersion\WinLogon"
  $regkey = ""
  $regkey = $reg.opensubkey($key)
  $keyValue = ""
  $keyValue = $regKey.GetValue('AutoAdminLogon')

  if ($keyValue = "1")
  {
    try
    {
      $textFile = New-Item -Path "c:empautologin" -Name $MachineName -ItemType "File"
    }
    catch
    {
      $msg = $_
      $msg
    }
  }
  $Results = $MachineName , $keyValue
  Write-host $Results

  #Output Below Here:
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In PowerShell = is an assignment operator, not a comparison operator. Change this line:

if ($keyValue = "1")

into this:

if ($keyValue -eq "1")

For more information see Get-Help about_Operators.

You're making this way too complicated, BTW. Something like this should suffice:

$keyname = 'SOFTWARE\Microsoft\Windows NT\CurrentVersion\WinLogon'

Import-Csv 'C:empmachines.csv' | % {
  $reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey("LocalMachine",
           $_.machinename)
  $key = $reg.OpenSubkey($keyname)
  $value = $key.GetValue('AutoAdminLogon')
  if ($value -eq "1") {
    $filename = Join-Path "c:empautologin" $_.machinename
    try {
      touch $filename
      $textFile = Get-Item $filename
    } catch {
      $_
    }
  }
  Write-Host ($_.machinename , $value)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...