Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium


PowerShell script that will display all users with administrative rigts on network.

Posted on 2007-07-23
Medium Priority
Last Modified: 2008-08-18
Here is what I want:

I am new IT person in my new company and one thing that I don't like here is that many users have admin privilegies (they are members of local administrator group). So I wanna Power Shell script which will show me all of the users that have administrator rigths or at least, list of all computers and accounts that are in local administrator group.

If someone can help in any way, thanks!
Question by:Cro0707
  • 4
  • 2
LVL 71

Expert Comment

by:Chris Dent
ID: 19575599

Stabbing in the dark, just in case ;)

The most likely reason that you haven't had a response to this is that very very few people have significant experience with PowerShell with ADSI, including myself.

I can give you what you want in VbScript, it'll take me around 30 minutes. But PowerShell is likely to take days of figuring out, especially since trivial things like getting Group Membership is so tricky.

Is it really important that this is done in PowerShell?

LVL 10

Author Comment

ID: 19580236
Hmmm... I know that this problem is not simple, but I was hope that someone will respond with some idea, because all speak about PS; like that tool let you do same thing like in VBS but with 10 times less code.

But it seam that's is not correct : )

If you could create script with VBS, this also be helpeful... I just wannted PS code, because I wanna learn PS : )
LVL 71

Expert Comment

by:Chris Dent
ID: 19580943

hehe yeah me too. ADSI is currently quite difficult to handle in it unfortunately. I'm sure there's a way to do it, but it's difficult trawling through documentation on it with few examples.

It does have access to the .NET classes for searching it's actually easy to modify simple attributes, it's only when we drop back to the WinNT interface needed for the local group enumeration it fails to work as I'd hoped.

For the sake of interest, this is how you can get all the computers in the domain in PowerShell:

$objDomain = New-Object System.DirectoryServices.DirectoryEntry;

$objSearcher = New-Object System.DirectoryServices.DirectorySearcher;
$objSearcher.SearchRoot = $objDomain;
$objSearcher.Filter = ("(objectClass=computer)");

$objResults = $objSearcher.FindAll();

ForEach ($objComputer in $objResults)
    "Connecting to " + $objComputer.Properties.name
    # $objAdministrators = [ADSI]("WinNT://" + $objComputer.Properties.name + "/Administrators, group");

It'll connect to the group with that, I just can't get it to enumerate the membership, very frustrating :)

It also doesn't currently have any way of checking if the host we want to query is actually there, that can result in rather long timeouts as it waits for the connection.

If you're interested in continuing with PowerShell you might find this program is well worth keeping and eye on:


I can make the RC1 version crash easily, still, it helps checking things through.

The VbScript version will follow.

Prepare for your VMware VCP6-DCV exam.

Josh Coen and Jason Langer have prepared the latest edition of VCP study guide. Both authors have been working in the IT field for more than a decade, and both hold VMware certifications. This 163-page guide covers all 10 of the exam blueprint sections.

LVL 71

Accepted Solution

Chris Dent earned 2000 total points
ID: 19580990

And here is a VbScript version, a little long but has plenty of error control and connection testing involved.

Output is a very simple CSV file.

Option Explicit

' Functions

Function GetLocalGroup(strServer, strGroupName)
      Dim objGroup, objMember
      Dim arrTemp()
      Dim intCounter

      On Error Resume Next : Err.Clear
      ' WScript.Echo "Connecting to: " & strServer
      Set objGroup = GetObject("WinNT://" & strServer & "/" & strGroupName & ", group")

      If Err.Number = 0 Then
            intCounter = 0
            For Each objMember in objGroup.Members
                  ReDim Preserve arrTemp(intCounter)
                  arrTemp(intCounter) = objMember.Name
                  intCounter = intCounter + 1
            GetLocalGroup = arrTemp
            GetLocalGroup = Array("")
      End If
      Set objGroup = Nothing
End Function

Function PingHost(strHost)
      ' Return Type: Boolean
      ' Basic Ping Test. Returns true if host responds.
      Dim objShell, objScriptExec, objStdOut
      Dim strOut
      Dim booReply
      Set objShell = CreateObject("WScript.Shell")
      Set objScriptExec = objShell.Exec("ping -n 1 " & strHost)
      Set objStdOut = objScriptExec.StdOut
      booReply = False
      Do Until objStdOut.AtEndOfStream
            strOut = objStdOut.ReadLine
            If InStr(strOut, "Reply from ") Then
                  booReply = True
            End If
      PingHost = booReply
      Set objStdOut = Nothing
      Set objScriptExec = Nothing
      Set objShell = Nothing
End Function

Function GetDNSAddresses(strComputerName)
      ' Return Type: Array
      ' Returns an Array containing each IP Address for a given Node Name from a
      ' DNS Query

      Dim objShell, objScriptExec, objStdOut
      Dim strIPAddress, strOut
      Dim arrIPAddresses

      Set objShell = CreateObject("WScript.Shell")
      Set objScriptExec = objShell.Exec("nslookup " & strComputerName)
      Set objStdOut = objScriptExec.StdOut
      strIPAddress = ""
      Do Until objStdOut.AtEndOfStream
            strOut = objStdOut.ReadLine
            If InStr(strOut, "Name:") Then
                  strIPAddress = objStdOut.ReadLine
                  If InStr(strIPAddress, "Address:") > 0 Then
                        strIPAddress = Trim(Replace(strIPAddress, "Address:", ""))
                  ElseIf InStr(strIPAddress, "Addresses:") > 0 Then
                        strIPAddress = Trim(Replace(strIPAddress, "Addresses:", ""))
                  End If
            End If
      GetDNSAddresses = Split(strIPAddress, ", ")
      Set objStdOut = Nothing
      Set objScriptExec = Nothing
      Set objShell = Nothing
End Function

' Subroutines

Sub GetComputersFromAD
      ' AD Query for Computer Objects.

      Const ADS_SCOPE_SUBTREE = 2

      Dim objConnection, objCommand, objRecordSet, objRootDSE
      Dim strComputerName

      Set objConnection = CreateObject("ADODB.Connection")
      objConnection.Provider = "ADsDSOObject"
      objConnection.Open "Active Directory Provider"

      Set objCommand = CreateObject("ADODB.Command")
      objCommand.ActiveConnection = objConnection

      Set objRootDSE = GetObject("LDAP://RootDSE")
      objCommand.CommandText = "SELECT distinguishedName, name " &_
            "FROM 'LDAP://" & objRootDSE.Get("defaultNamingContext") & "' WHERE objectClass='computer'"
      Set objRootDSE = Nothing

      objCommand.Properties("Page Size") = 1000
      objCommand.Properties("Timeout") = 600
      objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
      objCommand.Properties("Cache Results") = False

      Set objRecordSet = objCommand.Execute

      While Not objRecordSet.EOF
            strComputerName = objRecordSet.Fields("name")
            WriteAdministrators strComputerName


      Set objRecordSet = Nothing
      Set objCommand = Nothing
      Set objConnection = Nothing
End Sub

Sub WriteAdministrators(strComputerName)
      Dim strLine, strAdministrator
      Dim arrTemp, arrAdministrators

      ' Connectivity Test
      ' IP Address Test
      arrTemp = GetDNSAddresses(strComputerName)
      If UBound(arrTemp) = -1 Then
            Exit Sub
      End If

      ' Basic Connectivity Test
      If PingHost(strComputerName) = False Then
            Exit Sub
      End If

      arrAdministrators = GetLocalGroup(strComputerName, "Administrators")
      If arrAdministrators(0) <> "" Then
            strLine = strComputerName
            For Each strAdministrator in arrAdministrators
                  strLine = strLine & "," & strAdministrator
            objFile.WriteLine strLine
            ' WScript.Echo "Error Getting Administrators"
      End If
End Sub

' Main Code

Dim objFileSystem, objFile

Set objFileSystem = CreateObject("Scripting.FileSystemObject")
Set objFile = objFileSystem.OpenTextFile("ComputerReport.csv", 2, True, 0)


Set objFile = Nothing
Set objFileSystem = Nothing
LVL 10

Author Comment

ID: 19581112

thank you for your time, I really appreciate it. I will play with both examples!
LVL 71

Expert Comment

by:Chris Dent
ID: 19581117

Good luck :)


Featured Post

Free Backup Tool for VMware and Hyper-V

Restore full virtual machine or individual guest files from 19 common file systems directly from the backup file. Schedule VM backups with PowerShell scripts. Set desired time, lean back and let the script to notify you via email upon completion.  

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Background Still having to process all these year-end "csv" files received from all these sources (including Government entities), sometimes we have the need to examine the contents due to data error, etc... As a "Unix" shop, our only readily …
Utilizing an array to gracefully append to a list of EmailAddresses
Learn several ways to interact with files and get file information from the bash shell. ls lists the contents of a directory: Using the -a flag displays hidden files: Using the -l flag formats the output in a long list: The file command gives us mor…
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…

580 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question