klauern
7/25/2009 - 4:06 AM

Method to detect whether we are running from an elevated command-prompt under Vista/Win7 or Administrator in WinXP

Method to detect whether we are running from an elevated command-prompt under Vista/Win7 or Administrator in WinXP

#
# Method to detect whether we are running from an elevated command-prompt
# under Vista/Win7 or as part of the local Administrators group in WinXP.
#
def elevated?
  whoami = `whoami /groups` rescue nil
  if whoami =~ /S-1-16-12288/
    true
  else
    admin = `net localgroup administrators | find "%USERNAME%"` rescue ""
    if admin.empty?
      false
    else
      true
    end
  end
end

#
# A more terse version of the same thing.
#
def elevated?
  whoami = `whoami /groups` rescue nil
  if whoami =~ /S-1-16-12288/
    true
  else
    admin = `net localgroup administrators | find "%USERNAME%"` rescue ""
    admin.empty? ? false : true
  end
end