Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

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

Posted on 2013-05-23
6
Medium Priority
?
1,181 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 1000 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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 7

Accepted Solution

by:
BT15 earned 1000 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

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Question has a verified solution.

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

Recently we ran in to an issue while running some SQL jobs where we were trying to process the cubes.  We got an error saying failure stating 'NT SERVICE\SQLSERVERAGENT does not have access to Analysis Services. So this is a way to automate that wit…
Measuring Server's processing rate with a simple powershell command. The differences in processing rate also was recorded in different use-cases, when a server in free and busy states.
Learn the basics of modules and packages in Python. Every Python file is a module, ending in the suffix: .py: Modules are a collection of functions and variables.: Packages are a collection of modules.: Module functions and variables are accessed us…
The viewer will learn how to dynamically set the form action using jQuery.
Suggested Courses

876 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