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

x
?
Solved

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

Posted on 2007-07-23
6
Medium Priority
?
1,475 Views
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!
0
Comment
Question by:Cro0707
  • 4
  • 2
6 Comments
 
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?

Chris
0
 
LVL 10

Author Comment

by:Cro0707
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 : )
0
 
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)");
$objSearcher.PropertiesToLoad.Add("name");

$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:

http://www.powershellanalyzer.com/

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

The VbScript version will follow.

Chris
0
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

by:
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
            Next
            GetLocalGroup = arrTemp
      Else
            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
      Loop
      
      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
      Loop
      
      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
      
            objRecordSet.MoveNext
      Wend

      objConnection.Close

      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
            Next
                              
            objFile.WriteLine strLine
      Else
            ' 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)

GetComputersFromAD

Set objFile = Nothing
Set objFileSystem = Nothing
0
 
LVL 10

Author Comment

by:Cro0707
ID: 19581112
Chris-Dent,

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

Expert Comment

by:Chris Dent
ID: 19581117

Good luck :)

Chris
0

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