2
我正在寫一個ruby函數以從給定的DisplayName獲取UninstallString。當我給它一個現有的DisplayName來查找時,我的函數只能成功運行,當我給出不存在的東西時它崩潰。我不確定哪個變量需要檢查什麼條件(nil?空?),以便我可以向腳本中拋出一個異常,輸出'not found'消息而不是崩潰?Ruby Win32註冊表:當查找不存在的註冊表項時,系統找不到指定的文件
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>'