Solved

Powershell Script to return members of local admins group for all servers in specific OU

Posted on 2013-05-23
6
982 Views
Last Modified: 2013-06-27
Hi All

I have this powershell script that returns members of the admins group based on an input text file and it sppears to work well, however i would like to change it so the scope is an OU rather than an input file.


$Properties = "AdsPath","Name","Class","Description"

$Select = $Properties | %{  
  Invoke-Expression "@{n='$_';e={ `$_.GetType().InvokeMember('$_', 'GetProperty', `$Null, `$_, `$Null) }}"  
}
 
#$RunDate  = (get-date).tostring("MM_dd_yyyy")  
#$Time = Get-Date -format 'hh:mm'  
$Results = "C:\output\Localadmin.csv"  
 
Get-Content "C:\input\servers.txt"  | ForEach-Object {

  $ComputerName = $_
  $Group = [ADSI]("WinNT://$ComputerName/Administrators")  
  $Group.PsBase.Invoke("Members") | Select-Object ([Array](@{n='ServerName';e={ $ComputerName }}) + $Select)

} | Export-Csv "C:\output\Localadmin.csv" -NoTypeInformation

Open in new window


Could someone please show me what amendmants need to be made

Many Thanks
0
Comment
Question by:ncomper
6 Comments
 
LVL 7

Expert Comment

by:BT15
ID: 39191252
when you say OU, you mean a machine OU?

if you use the Microsoft Active Directory commandlets (import-module activedirectory) available for the newer versions of windows (not XP/2003 basically) you can use the GET-ADCOMPUTER commandlet like so (replacing the one line you have above that imports the csv)


get-adcomputer -filter * -SearchBase "cn=computers,dc=contoso,dc=com" | select name | ForEach-Object {

Open in new window


if you need to use XP, then you can get commandlets from Quest. I believe the command is get-qadcomputer
0
 
LVL 40

Assisted Solution

by:Subsun
Subsun earned 250 total points
ID: 39191273
You may use Get-ADComputer command to get the computer list from OU..
Try..
$Properties = "AdsPath","Name","Class","Description"

$Select = $Properties | %{  
  Invoke-Expression "@{n='$_';e={ `$_.GetType().InvokeMember('$_', 'GetProperty', `$Null, `$_, `$Null) }}"  
}
 
#$RunDate  = (get-date).tostring("MM_dd_yyyy")  
#$Time = Get-Date -format 'hh:mm'  
$Results = "C:\output\Localadmin.csv"  
 
Get-ADComputer -filter * -SearchBase "CN=Computers,DC=Domain,DC=com"  | ForEach-Object {

  $ComputerName = $_.Name
  $Group = [ADSI]("WinNT://$ComputerName/Administrators")  
  $Group.PsBase.Invoke("Members") | Select-Object ([Array](@{n='ServerName';e={ $ComputerName }}) + $Select)

} | Export-Csv "C:\output\Localadmin.csv" -NoTypeInformation

Open in new window

0
 
LVL 5

Author Comment

by:ncomper
ID: 39191408
excellent thanks, just tested that and it worked great, if possible im after one more improvement on it

When i run it i got about 10 instances of the below message, im guessing this was because it could not connect to the server for various reasons, is it possible to get it to record which servers it was trying to connect to, i suspect they are just AD objects that do not exist but it would be nice to know

Exception calling "Invoke" with "2" argument(s): "The network path was not found.
"
At C:\psscripts\localadmin1.ps1:15 char:23
+   $Group.PsBase.Invoke <<<< ("Members") | Select-Object ([Array](@{n='ServerName';e={ $ComputerName }}) + $Select)
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException


Many Thanks
0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
LVL 7

Accepted Solution

by:
BT15 earned 250 total points
ID: 39191460
I'll assume you used Subsun's code

you can use the test-connection commandlet before attempting to check the server like so

$Properties = "AdsPath","Name","Class","Description"

$Select = $Properties | %{  
  Invoke-Expression "@{n='$_';e={ `$_.GetType().InvokeMember('$_', 'GetProperty', `$Null, `$_, `$Null) }}"  
}
 
#$RunDate  = (get-date).tostring("MM_dd_yyyy")  
#$Time = Get-Date -format 'hh:mm'  
$Results = "C:\output\Localadmin.csv"  
 $failed = @()
Get-ADComputer -filter * -SearchBase "CN=Computers,DC=Domain,DC=com"  | ForEach-Object {

  $ComputerName = $_.Name
  if (test-connection $computername -quiet){
  $Group = [ADSI]("WinNT://$ComputerName/Administrators")  
  $Group.PsBase.Invoke("Members") | Select-Object ([Array](@{n='ServerName';e={ $ComputerName }}) + $Select)


} 
}else{
$failed = @(
$failed
$computername
)
} | Export-Csv "C:\output\Localadmin.csv" -NoTypeInformation
$failed | sc c:\output\failedservers.txt

Open in new window

0
 
LVL 40

Expert Comment

by:Subsun
ID: 39191557
I tried to add some error handling inline with the same report.. try this and see if it works for you..
$ErrorActionPreference = "SilentlyContinue"
$Properties = "AdsPath","Name","Class","Description"

$Select = $Properties | %{  
  Invoke-Expression "@{n='$_';e={ `$_.GetType().InvokeMember('$_', 'GetProperty', `$Null, `$_, `$Null) }}"  
}
 
#$RunDate  = (get-date).tostring("MM_dd_yyyy")  
#$Time = Get-Date -format 'hh:mm'  
$Results = "C:\output\Localadmin.csv"  
Get-ADComputer -filter * -SearchBase "CN=Computers,DC=Domain,DC=com"  | ForEach-Object {
	$Error.Clear()
	$ComputerName = $_.Name
  If (Test-Connection $ComputerName -Count 2){
	$Group = [ADSI]("WinNT://$ComputerName/Administrators")
	$Group.PsBase.Invoke("Members") | Select-Object ([Array](@{n='ServerName';e={ $ComputerName }}) + $Select)
	If ($Error) {"" | Select-Object @{n='ServerName';e={ $ComputerName }},AdsPath,Name,Class,@{n="Description";e={$error[0].Exception.Message}}}
	}
	Else {"" | Select-Object @{n='ServerName';e={ $ComputerName }},AdsPath,Name,Class,@{n="Description";e={$error[0].Exception.Message}}}
} | Export-Csv "C:\output\Localadmin.csv" -NoTypeInformation

Open in new window

0
 
LVL 3

Expert Comment

by:Mahoney-84
ID: 39191815
If you don't want to dirty up your output file - This will just write the errors to the host
$Properties = "AdsPath","Name","Class","Description"
$Error.Clear()
$Select = $Properties | %{
	Invoke-Expression "@{n='$_';e={ `$_.GetType().InvokeMember('$_', 'GetProperty', `$Null, `$_, `$Null) }}" 
}
 
#$RunDate  = (get-date).tostring("MM_dd_yyyy")  
#$Time = Get-Date -format 'hh:mm'
$Results = "C:\output\Localadmin.csv"  
 
GC c:\servers.txt | ForEach-Object {
 	$ComputerName = $_
	$Group = [ADSI]("WinNT://$ComputerName/Administrators")
	#if($error[0] -like "*The network*"){"$_`n" | Out-File "c:\output\FailedLocaladmin.csv"}
	Try{$Group.PsBase.Invoke("Members") | Select-Object ([Array](@{n='ServerName';e={ $ComputerName }}) + $Select)}
	Catch{$err = "Failed to Connect $ComputerName";Write-Host $err}


	} | Export-Csv "C:\output\Localadmin.csv" -NoTypeInformation

Open in new window

0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Hi all.   The other day I had to change the passwords for a bunch of users on the fly. Because they were so many, I decided to do it in an automated way and I would like to share it with you all.   If you are not doing it directly in a Domain Co…
How to sign a powershell script so you can prevent tampering, and only allow users to run authorised Powershell scripts
Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…

747 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

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now