[Win32utils-devel] Getting a list of groups for a given user

Daniel Berger djberg96 at gmail.com
Mon Mar 2 00:54:08 EST 2009


Hi,

How does this look for finding a list of groups for a particular user?

This is for the sys-admin library. Assume "self.name" is pretty much
the same thing as Etc.getlogin would return.

# admin.rb
Class User
   def groups(domain=nil)
         host = Socket.gethostname
         cs = "winmgmts:{impersonationLevel=impersonate}!"
         cs << "//#{host}/root/cimv2"

         begin
            wmi = WIN32OLE.connect(cs)
         rescue WIN32OLERuntimeError => err
            raise Error, err
         end

         if domain
            query = " select * from Win32_GroupUser where partcomponent = "
            query <<
"\"Win32_UserAccount.Domain='#{domain.upcase}',Name='#{self.name}'\""
         else
            query = " select * from Win32_GroupUser where partcomponent = "
            query <<
"\"Win32_UserAccount.Domain='#{host.upcase}',Name='#{self.name}'\""
         end

         array = []

         wmi.execquery(query).each{ |groupuser|
            array << groupuser.GroupComponent.split('=').last.tr('"', '')
         }

         array
      end
end

Regards,

Dan


More information about the win32utils-devel mailing list