rismoney
rismoney

Reputation: 531

ruby registry checking

I have the following snippet which I am trying to use to validate registry keys (OS is Windows 2008R2 or Win7)

def value_exists?(path,key)
  reg_type = Win32::Registry::KEY_READ 
  Win32::Registry::HKEY_LOCAL_MACHINE.open(path, reg_type) do |reg|
    begin
      regkey = reg[key]
      return true
    rescue
      return false
    end
  end
end

When I do the following 2 commands the output is expected (in my case false is returned) :

puts(value_exists?("SYSTEM\\CurrentControlSet\\Control\\Session Manager\\",'PendingFileRenameOperations'))
puts(value_exists?("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Component Based Servicing\\",'RebootPending'))

When I perform a

puts(value_exists?("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WindowsUpdate\\Auto Update\\",'RebootRequired')) 

I get the following error

C:/Ruby187/lib/ruby/1.8/win32/registry.rb:528:in `open': The system cannot find the file specified. (Win32::Registry::Error)
        from C:/Ruby187/lib/ruby/1.8/win32/registry.rb:608:in `open'
        from ./reg2.rb:7:in `value_exists?'
        from ./reg2.rb:21

I don't really understand what to do to make this work. I suspect it might have something to do with the systems being x64 and it failing to find the key in the right location. but I am not sure what I need to do to remedy this.

Thanks for your help in advance!

Upvotes: 8

Views: 5064

Answers (4)

FilBot3
FilBot3

Reputation: 3718

You could also try using ENV. It acts as a hash, and allows you to do hash functions.

ENV.has_key?("CUSTOM_PATH") #=> Should return TRUE or FALSE

and to list all the available keys

ENV.each do |k, v|
    puts "#{k} is related to #{v}"
end

I hope that helps.

Ruby-Doc Core-2.0.0 - ENV

Upvotes: 0

rismoney
rismoney

Reputation: 531

I figured it out - http://msdn.microsoft.com/en-us/library/windows/desktop/aa384129(v=vs.85).aspx

reg_type = Win32::Registry::KEY_READ | 0x100

This solved the issue! My guess is that you guys were not testing on x64?

Upvotes: 8

ray_linn
ray_linn

Reputation: 1392

I can not duplicate your issue on ruby 1.9.2 P286, three false are returned as expected even keys does not exist.

You can compare the source code under <ruby path>\lib\ruby\<version>\win32 to find out the change, and update by yourself.

Upvotes: 0

saihgala
saihgala

Reputation: 5774

your issue is that following path SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WindowsUpdate\\Auto Update\\ does not exist in your registry. Have you checked it using regedit?

You should modify your code to -

def value_exists?(path,key)
    reg_type = Win32::Registry::KEY_READ 
    begin
        Win32::Registry::HKEY_LOCAL_MACHINE.open(path, reg_type) {|reg| regkey = reg[key]}
    rescue
        false
    end
end

Upvotes: 1

Related Questions