Solved

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

Posted on 2013-05-23
6
1,071 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
How Do You Stack Up Against Your Peers?

With today’s modern enterprise so dependent on digital infrastructures, the impact of major incidents has increased dramatically. Grab the report now to gain insight into how your organization ranks against your peers and learn best-in-class strategies to resolve incidents.

 
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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Set OWA language and time zone in Exchange for individuals, all users or per database.
In threads here at EE, each comment has a unique Identifier (ID). It is easy to get the full path for an ID via the right-click context menu. However, we often want to post a short link within a thread rather than the full link. This article shows a…
Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …

735 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