ruby注册表检查

时间:2012-11-26 03:56:22

标签: ruby windows registry

我有以下代码片段,我尝试使用它来验证注册表项(操作系统是Windows 2008R2或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

当我执行以下2个命令时,预期输出(在我的情况下返回false):

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

当我执行

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

我收到以下错误

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

我真的不明白如何做到这一点。我怀疑它可能与x64系统有关,而且无法在正确的位置找到密钥。但我不确定我需要做些什么来解决这个问题。

提前感谢您的帮助!

4 个答案:

答案 0 :(得分:8)

我想通了 - http://msdn.microsoft.com/en-us/library/windows/desktop/aa384129(v=vs.85).aspx

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

这解决了这个问题!我的猜测是你们没有在x64上测试?

答案 1 :(得分:1)

您的问题是您的注册表中不存在以下路径SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WindowsUpdate\\Auto Update\\。你用regedit检查了它吗?

您应该将代码修改为 -

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

答案 2 :(得分:0)

我无法在ruby 1.9.2 P286上复制你的问题,按预期返回三个false,即使密钥不存在。

您可以比较< ruby​​ path> \ lib \ ruby​​ \< version> \ win32下的源代码,找出更改并自行更新。

答案 3 :(得分:0)

您也可以尝试使用ENV。它充当哈希,并允许您执行哈希函数。

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

并列出所有可用的密钥

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

我希望有所帮助。

Ruby-Doc Core-2.0.0 - ENV