Solved

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

Posted on 2013-05-23
6
1,119 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
Certified OpenStack Administrator Course

We just refreshed our COA course based on the Newton exam.  With 14 labs, this course goes over the different OpenStack services that are part of the certification: Dashboard, Identity Service, Image Service, Networking, Compute, Object Storage, Block Storage, and Orchestration.

 
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

Certified OpenStack Administrator Course

We just refreshed our COA course based on the Newton exam.  With 14 labs, this course goes over the different OpenStack services that are part of the certification: Dashboard, Identity Service, Image Service, Networking, Compute, Object Storage, Block Storage, and Orchestration.

Question has a verified solution.

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

My attempt to use PowerShell and other great resources found online to simplify the deployment of Office 365 ProPlus client components to any workstation that needs it, regardless of existing Office components that may be needing attention.
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…
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…
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…

636 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