[Win32utils-devel] Getting a home directory on windows

Daniel Berger djberg96 at gmail.com
Sun Nov 14 10:51:37 EST 2010


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



More information about the win32utils-devel mailing list