Daniel Berger
2010-Nov-14 15:51 UTC
[Win32utils-devel] Getting a home directory on windows
What do you think?
require ''win32ole''
require ''etc''
def get_windows_home_directory
user = Etc.getlogin
# Try the domain account first
adsi = WIN32OLE.connect("WinNT://#{host}/#{user},user")
home = adsi.homedirectory
# If the homedirectory was blank, try the local account
unless home.size?
wmi = WIN32OLE.connect("winmgmts://")
sql = "select * from win32_useraccount where name =
''#{name}''"
sid = nil
wmi.execquery(sql).each{ |u| sid = u.sid }
# If the sid couldn''t be found for some reason then fall back to
using
ENV.
# Otherwise use the registry value.
if sid.nil?
home = ENV[''USERPROFILE''] ||
ENV[''HOME'']
else
require ''win32/registry''
key = "SOFTWARE\\Microsoft\\Windows
NT\\CurrentVersion\\ProfileList\\"
+ sid
# If this fails it probably means the registry value could not be
found
# and we again fall back to using ENV.
begin
Win32::Registry::HKEY_LOCAL_MACHINE.open(key) do |reg|
home = reg[''ProfileImagePath'']
end
rescue Win32::Registry::Error
home = ENV[''USERPROFILE''] ||
ENV[''HOME'']
end
end
end
home
end