Monday, August 16, 2010

AD Group Report - List Group Members in Active Directory–PowerShell Script

Updated Script - http://portal.sivarajan.com/2011/10/search-ad-collect-local-admin-group.html

Script #1

This script can be used to list group membership in Active Directory. Input – Group DN

image

As you can see on the following screenshot, this script uses an input file called Glist.csv which contains all group names.

image

You will see the output on the screen as well as in the GroupDetails.csv file.

image

You can download the script from the following locations.  Rename the file to .PS1

http://www.sivarajan.com/scripts/Group_Members.txt

http://gallery.technet.microsoft.com/scriptcenter/dcc9432e-d541-4be2-a39c-637c8d4c9fd0


Script #2

Modified Script – This script will prompt you for the Group distinguishedName (DN). 

image


Script #3

$OutPutFile = New-Item -type file -force "D:\Scripts\GroupDetails.csv"

#update filter based on your requirement

# 2 Global distribution group

# 4 Domain local distribution group

# 8 Universal distribution group

# -2147483646 Global security group

# -2147483644 Domain local security group

# -2147483640 Universal security group

$ObjFilter = "(&(objectCategory=Group)(|(groupType=2)(groupType=4)(groupType=8)))"

$objSearch = New-Object System.DirectoryServices.DirectorySearcher

$objSearch.SearchRoot = "LDAP://OU=DLs,DC=Sivarajan,DC=com"

$objSearch.PageSize  = 10000

$objSearch.Filter = $ObjFilter

$Results = $objSearch.FindAll()

foreach ($Result in $Results){

    $Item = $Result.Properties

    Write-host $Item.cn

$Item.cn | Out-File $OutPutFile -encoding ASCII -append

    foreach ($Member in $Item.member) {

               Write-host "$Member"

$Member | Out-File $OutPutFile -encoding ASCII -append

    }

}


Script #4
 

Nested Group Report - This script will search AD for all security groups and generate a nested group  details. Output will contain only Groups.

image

Script

Clear
$AllGroupNames = Get-ADGroup -Filter {(GroupCategory -eq 'security')} #-SearchBase 'DC=domain1,DC=com'
#Gnames - contins all Security group details
    foreach ($GNamet in $AllGroupNames)
    {
    Write-Host "Parent Group Name -" $GNamet.Name, $GNamet.GroupScope
    #GNamet contins all Group properties
    $Gname = $GNamet.Name
    #$Gname contians only group names
    $AllGmembers = Get-ADGroupMember -identity $Gname
    #$AllGmembers - memeber details from each security group
        foreach ($GMemebr in $AllGmembers) #Loop for verifying each member type
            {
                If ($GMemebr.objectClass -eq "Group") #verifying each member type. 
                {
                    $ChildGroupProp = Get-ADGroup -Identity $GMemebr
                    Write-Host "Child Group Member(s)-" $GMemebr.name, $ChildGroupProp.GroupScope -ForegroundColor Green
                }
            }

    }

 

Output

Output will contain parent and child group and group type.

image


58 comments:

Hi Santosh,

Do you have any disc.vouchers for MCTS 70-432 now? iam planning to finish it off this weekend.

Regards,
Vinodh
Chennai,India

Could you elaborate on the contents of Glist.csv? I have an AD with no OUs created and I am not sure what to put there.

Also, does the DC=local indicate the script is run on the DC? Should I put something else to run it remotely?

It is the DN (Distinguished Name) of the group. If you have Windows 2008 or R2, you can go to the properties of the group and select the “Attribute” Tab, you will see the Distinguished Name (DN) there.

DC is the domain name. In my example, my domain name is “Infralab.local”

“Test1” is the group name. It is inside the “Test” OU.

So the DN of the Group = “name of the group, name of OU, domain name”

http://msdn.microsoft.com/en-us/library/windows/desktop/aa366101(v=vs.85).aspx

http://technet.microsoft.com/en-us/library/cc776019(WS.10).aspx

Please let me know if you need more clarification.

How do I select the group only accounts enable

What do you mean by “group only accounts enable”? What are you trying to accomplish?

He wants to have only active accounts in the group.
'Where userAccountControl = 512'
http://support.microsoft.com/kb/305144
512 0x0200 NORMAL_ACCOUNT

Hi Santhosh,

I get this error when i run your script..Please help..i am a newbie to powershell

Windows PowerShell
Copyright (C) 2009 Microsoft Corporation. All rights reserved.

PS C:\Windows\system32> $GFile = New-Item -type file -force "C:\Scripts\GroupDetails.csv"
PS C:\Windows\system32> Write-Host "Schema Admins" -ForegroundColor Red
Schema Admins
PS C:\Windows\system32> $GName = Read-Host
$group = [ADSI] "LDAP://$GName"
PS C:\Windows\system32> $group.cn
PS C:\Windows\system32> $group.cn | Out-File $GFile -encoding ASCII -append
PS C:\Windows\system32> foreach ($member in $group.member)
>> {
>> $Uname = new-object directoryservices.directoryentry("LDAP://$member")
>> $Uname.cn
>> $Uname.samaccountname
>> $Uname.samaccountname $Uname.cn | Out-File $GFile -encoding ASCII -append
>> }
>>
Unexpected token 'Uname' in expression or statement.
At line:6 char:41
+ $Uname.samaccountname $Uname <<<< .cn | Out-File $GFile -encoding ASCII -append
+ CategoryInfo : ParserError: (Uname:String) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : UnexpectedToken

As you know, this script is not searching AD for “active” users. In that case, you need validate the Admin group result against AD.

Hi Santosh,

I am also getting the same error "Unexpected token 'Uname' in expression or statement"

What do you mean by "you need validate the Admin group result against AD"

Please post the complete script here.

Since this script is not searching or validating the result against AD, you need to compare the local admin member details against AD.

Very useful Santhosh, modified to automate the creation of the DN's file (could probably use an array, but I'm not there yet. Also modified the output to display additional fields.

<# from a list of group names (GroupName.txt), generate a list with the group's DN, (Glist.csv),
import this list and generate list of group members (GroupDetails.csv) for each group
#>

$GroupsList = "C:\Glist.csv" #list with DN's
$GFile = New-Item -type file -force "C:\GroupDetails.csv" #list with group members

#original list with group names
foreach($item in (gc "C:\GroupName.txt")){

get-QADGroup $item | select DN | Export-Csv $GroupsList

Import-CSV $GroupsList | ForEach-Object {

# .DN - this is the header used for the list
$GName = $_.DN

# query group
$group = [ADSI] "LDAP://$GName"
$group.cn
$group.cn | Out-File $GFile -encoding ASCII -append
foreach ($member in $group.member)
{
$Uname = new-object directoryservices.directoryentry("LDAP://$member")
$Uname.sAMAccountName
$Uname.displayName
$Uname.userPrincipalName
$Outline = "`""
$Outline +=$Uname.sAMAccountName
$Outline += "`",`""
$Outline += $Uname.displayName
$Outline += "`",`""
$Outline += $Uname.userPrincipalName
$Outline += "`""

$Outline | Out-File $GFile -encoding ASCII -append
}
}
}

Thanks. It looks like you are using some Quest cmdlets also.

Thanks for sharing your version of the script.

Is there a way to limit output to just groups that are members, and not users or computers, is there a way to filter this output for that?

I'm trying Where {objectclass -eq 'group'} and getting nothing...

Santosh,

I am having difficulty with the GList. Can you offer some advice please?

GroupName
"OU=CTX-Office2007Suite,CN=Groups,CN=SEC-Groups,CN=Site,DC=mydomain,DC=com"

TEK,
Please post the error message here

Palmcroft,
Yes. You can. What is your actual requirement?

Great script that potentially can save my a lot of work. Just one questrion from a Powershell-virgin: Is there a way I can modify the script to only show the users that are members and not groups that are member of other groups?

I eventually got this script to work after much fuddling around. I comment that the script leaves out a LOT of preliminary knowledge and information. I work in a large enterprise environment and I only care about my Site's groups. So I used the old ldp.exe (from the Windows 2000 Server Resource Kit) to inspect the Distinguished Names of each of my groups. Then I used Active Directory Users and Computers "Export" function to dump my groups into text file which I opened in Excel. I then appended the necessary Distinguished Name information to create the GList.csv text file. It still bloody didn't work until I added the "GroupName" header at the top of the csv file. I then debugged it in Windows PowerShell Integrated Scripting Environment (ISE) program and finally got it to dump the desired text file of users. I thank the script authors but comment that they should expect the audience to be much less expert than themselves in respect of knowledge of LDAP DN paths, etc. and should provide step-by-step illustrated instructions for "aspiring" Systems Admins like myself seeking enlightenment.

Mr Maw is there any step-by-step tutorial to use for this procedure?

Is there anyway I can add the managedby field to the output of this script?

Cheers

Jon

Yes. Just add $Uname.managedby

Maw,
What do you mean by “of preliminary knowledge and information”? What are you expecting to see?

Hi thanks, I worked it out I needed $Uname.manager...however it returns the full distinguished name of the manager back, e.g. CN=Smith\, Steve,OU=Advanced Users,DC=DOMAIN,DC=ORG,DC=UK
Can I filter this so it just outputs the display name of the manager?

Thanks again

Yes. It was Manager (http://portal.sivarajan.com/2010/07/aduc-and-ldap-reference-sheet.html)

There are many ways you can get the name or some other attribute values. Here is an example using the same logic:

Store manager value to a variable and get the CN.

$temp1 = $Uname.manager
$temp2 = [ADSI] "LDAP://$temp1"
$temp2.cn

$temp2.cn will be display name

How do you get the output file to differentiate Groups and users? IE Upper for Groups or Comma infront of Users?

Is there any way to add some spaces in front of the users names so at a glance you can tell the difference between users and groups? i.e.
"Group1"
"Username1"
"Username2"

I think he is referring to the fact that it's easy for a person totally unfamiliar with Powershell to overlook the fact that the GList.csv file needs to be manually created and is just a reference point. Also that the file needs to have the exact information and format.

I'm totally new to powershell as well, and if I hadn't seen his post, I would probably still be lost.

I´ve made a little modification to your script in order to display :
Group ; User in the same line and easily filter with excel:

$GFile = New-Item -type file -force "C:\Scripts\GroupDetails.csv"
Import-CSV "C:\Scripts\GList.txt" | ForEach-Object {
$GName = $_.GroupName
$group = [ADSI] "LDAP://$GName"
$group.cn

$group.cn | Out-File $GFile -encoding ASCII -append

foreach ($member in $group.member)
{
$data = $group.cn,";",$Uname.cn
$Uname = new-object directoryservices.directoryentry("LDAP://$member")
Write-Host $data
$Uname.cn | Out-File $GFile -encoding ASCII -append

}
}

Thanks Carlos! Thanks for sharing this.

Hi Santosh

Thanks for the great scripts. I am currently running script 4 on one of my servers and as much i like the display of parent and child groups on screen is there anyway to export this to a file.

Please advise.

Dears,

I am getting mentioned below error while running this script. Please help me

Unexpected token 'Uname' in expression or statement.
At C:\group.ps1:12 char:32
+ $Uname.samaccountname $Uname <<<< .cn | Out-File $GFile -encoding ASCII -append
+ CategoryInfo : ParserError: (Uname:String) [], ParseException
+ FullyQualifiedErrorId : UnexpectedToken

Could you elaborate on the contents of Glist.csv? I have an AD with no OUs created and I am not sure what to put there.

Also, does the DC=local indicate the script is run on the DC? Should I put something else to run it remotely?

- - - - Choi Minzi - - - -
1 800 273 8255 lyrics

I have to fetch All group membership of specific user in loop used in powershell from multiple domains

Hi senthosh
I get this error when I run your script..
Please help..i am a new to powershell

New-Item : A positional parameter cannot be found that accepts argument 'Import-CSV'.
At line:1 char:10
+ $GFile = New-Item -type file -force "C:\Scripts\GroupDetails.csv" Imp ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [New-Item], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.NewItemCommand



If you are looking for luxurious Handbags bearing designer labels, Vitapress.By is the destination to visit. It is a website where you will find genuine leather Louis Vuitton Bags of luxury handbags from famed brands like Balenciaga, Celine, Dior,Hermes handbags, Fendi and Saint Laurent among others. And the sale price and high quality has won a great reputation all over the world.Also ,The Rolex Watches It offers free shipping for all orders and countries.






نقل عفش من الدمام الى الرياض نقل عفش من الدمام الى الرياض
ارخص نقل عفش بمكة ارخص نقل عفش بمكة
نقل عفش من جدة الى الاردن نقل عفش من جدة الى الاردن

Medical assignment writing projects are very difficult to complete and many students are always searching for Help with Medical Assignment companies to help them complete their medical coursework assignments.

Online religion research paper writing services are very difficult to complete and many students are always searching for Religion Research Paper Services companies to help them complete their custom religion essay writing services.

Finding the best Help with Medical Assignment is not easy unless one is keen to establish a professional medical assignment help & medical homework help online.

Online logistics management writing services are very difficult to complete and many students are always searching for Logistics Writing Services Online to help them complete their logistics coursework writing services and logistic research paper services.

Custom Social Science Writing Services is very popular for students in search for social science essay services and social science research paper services.

Buy descriptive essay help online seekers has been on the rise lately since most learners need Descriptive Essay Writing Services, descriptive essay writing help and descriptive essay services.

Do we have any ps script to read/writer Bios settings

Those ESL assignment writing services have an advantage of hiring the best English language coursework writing service company that is familiar with ESL assignment help services for their English Language Writing Services.

Finding the best biological science paper writing help and Biological Science Writing Services is not easy unless one is keen to establish a reliable biological science research paper provider & biological science coursework writing services.

The effectiveness of IEEE Project Domains depends very much on the situation in which they are applied. In order to further improve IEEE Final Year Project Domains practices we need to explicitly describe and utilise our knowledge about software domains of software engineering Final Year Project Domains for CSE technologies. This paper suggests a modelling formalism for supporting systematic reuse of software engineering technologies during planning of software projects and improvement programmes in Final Year Projects for CSE.

Software management seeks for decision support to identify technologies like JavaScript that meet best the goals and characteristics of a software project or improvement programme. JavaScript Training in Chennai Accessible experiences and repositories that effectively guide that technology selection are still lacking.

Aim of technology domain analysis is to describe the class of context situations (e.g., kinds of JavaScript software projects) in which a software engineering technology JavaScript Training in Chennai can be applied successfully

The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training

Thanks for sharing such an Amazing information, I Couldn't leave without reading your blog. I have read another good blog, I think you have read it too. click here Lexmark Printer helpdesk

That’s a nice article, thank you for a great article. It helped me a lot. Keep it up Must Visit Trend Micro helpdesk bellen

Hi your post is very nice and i am greatful to you for sharing this post with us.here i want to share some information about Norton Antivirus.As we all know how much Norton Antivirus is usefull for our laptops and mobiles.so whenever you have any query regarding Norton or need any assistance how to run or any information that time please visit over this site-norton Antivirus technische ondersteuning


Hi your post is really appreciatable.I really thankful for this post .here i would llike to share some information about HP Printer.We can resolve the smallest problem on same time If you are facing any problem relate to your HP Printer's so this is the right place to get smallest information about HP PRINTER for the further information please visit on our website- hp printer technische ondersteuning

Hi thankyou for this great helpful information.this information is really useful at today's time.you had easily explained whole information in a short note.now i want to share some information about avast antivirus.So if you are facing any problem regarding Avast so you can simply visit on our site-avast technische ondersteuning

Hi this post is very nice.finally i got all those information what i really wanted to know. thankyou for sharing this usefull information.here i want to share the information about mcafee security. as we all have been digitalied and we do multiple works together so if you face any problem or need any assist about MCAFEE so pleae visit over this site-mcafee Antivirus technische ondersteuning

hi, your post is very helpful for me. Finally, I found exactly what i want. If need information regarding printers then you can visit our site Xerox Printer klantenservice nummer belgie for help.

hi, Your post is very helpful for me, If you want to know more about antivirus then you can visit our site Canon Printer belgie contacteren for help.

hi, Your post is very helpful for me,finally i got exactly what I want. If you want to know more about antivirus then you can visit our site Bitdefender contacteren help.

hi, Your post is very helpful for me, finally i found exactly what i want , If you want to know more about antivirus then you can visit our site Kaspersky technische ondersteuning for help.

Post a Comment

Popular Posts

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More