Ruby Win32 Registry:在查找不存在的注册表项时,系统找不到指定的文件

时间:2014-03-14 00:02:34

标签: ruby registry

我正在编写一个ruby函数来从给定的DisplayName获取UninstallString。我的函数只有在我给它一个现有的DisplayName才能找到它时才会成功运行,当我给出一些不存在的东西时它会崩溃。我不确定检查哪个条件的变量(nil?empty?)所以我可以在我的脚本中抛出一个异常,打印一条消息' not found'而不是崩溃?

require 'win32/registry'

def get_uninstallstring(app_name)

  paths = [ "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall",
            "Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall",
            "Software\\Wow6464Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall"  ]
  access_type = Win32::Registry::KEY_ALL_ACCESS

  paths.each do |path|         # This is line 9
    Win32::Registry::HKEY_LOCAL_MACHINE.open(path, access_type) do |reg|
      reg.each_key do |key|
        k = reg.open(key) 
        app = k['DisplayName'] rescue nil
        if app == app_name
          str = k['UninstallString'] rescue nil
          return str
        end
      end
    end
  end
  return false
end

puts get_uninstallstring("ABC")    # This is line 24

以下是错误输出:

C:/ruby/1.9.1/win32/registry.rb:385:in `open': The system cannot find the file specified. (Win32::Registry::Error)
        from C:/heliopolis/opscode/chef/embedded/lib/ruby/1.9.1/win32/registry.rb:496:in `open'
        from test.rb:10:in `block in get_uninstallstring'
        from test.rb:9:in `each'
        from test.rb:9:in `get_uninstallstring'
        from test.rb:24:in `<main>'

1 个答案:

答案 0 :(得分:2)

所以我自己找到了一个解决方案。在实际获取其值之前,我必须编写另一个函数来检查密钥是否存在于给定路径中。

def key_exists?(path)
  begin
    Win32::Registry::HKEY_LOCAL_MACHINE.open(path, ::Win32::Registry::KEY_READ)
    return true
  rescue
    return false
  end
end

这是修改后的get函数:

  paths.each do |path| 
    if key_exists?(path)
      Win32::Registry::HKEY_LOCAL_MACHINE.open(path, access_type) do |reg|
        reg.each_key do |key|
          k = reg.open(key)
          app = k['DisplayName'] rescue nil
          if app == app_name
        return k['UninstallString'] rescue nil
          end
        end
      end
    else
      return false
    end
  end