Solved

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

Posted on 2013-05-23
6
1,017 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
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 
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

Does Powershell have you tied up in knots?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

Question has a verified solution.

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

The article will show you how you can maintain a simple logfile of all Startup and Shutdown events on Windows servers and desktops with PowerShell. The script can be easily adapted into doing more like gracefully silencing/updating your monitoring s…
This article will help you understand what HashTables are and how to use them in PowerShell.
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 create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

813 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

18 Experts available now in Live!

Get 1:1 Help Now