PS script to enumerate 25 OUs, look for 2 groups and pull membersl

Hi all.
I look at this question and know that to you PS experts it's an eay one - but not all of us pick up scripting that easy (I did offer to pay for training via a EE-gig lst year, but nothing really came of it ;0)

So, i have 25 OUs under the UK parent OU. Flat straucture here - all 25 OUs under UK. These OUs have many groups assigned to them. You know the thing, it's got a bit out of contol. What i need is a script that can loop through all 25 OUs looking for 2 groups called 'UKSouth' and UKNorth' and from here do 2 actions. Output the group names to a spreadsheet for each OU where they are found and also record the list of users in those groups. Is this something easily achieveble?
Appreciate your looking thank you.
LVL 1
Jay ThomasAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Jose Gabriel Ortega CastroCEO Faru Bonon IT - EE Solution ExpertCommented:
Hi what version is your Windows server (Active Directory)?
Jay ThomasAuthor Commented:
Hi, sorry, should have mentioned, it's 2008 R2
Jose Gabriel Ortega CastroCEO Faru Bonon IT - EE Solution ExpertCommented:
I'd need also the Domain name and the Distinguished name of your "UK" OU.
SD-WAN: Making It Work for You

As bandwidth requirements and Internet costs grow, businesses naturally want to manage budgets by reducing reliance on their most expensive connection types. Learn more about how to make SD-WAN work for your business in our on-demand webinar!

Jay ThomasAuthor Commented:
Hi, so it's external facing domain. Could we call it contoso.com and a DN of "ou=uk,dc=contoso,dc=com
I could change there after? Hope this doesn't show a miss trust ???
Jose Gabriel Ortega CastroCEO Faru Bonon IT - EE Solution ExpertCommented:
Nope, it doesn't really matter I'd do the logic to find that out in the script. Give me a bit. We gotta go step by step.
Jay ThomasAuthor Commented:
Thank you very much
oBdACommented:
Try this; the first two columns will have the group information, the rest the respective members.
'UKSouth', 'UKNorth' | Get-ADGroup | ForEach-Object {
	$GroupOU = ($_.DistinguishedName -split ',(?=OU=)', 2)[1]
	$GroupName = $_.Name
	$_ | Get-ADGroupMember | Select-Object -Property @{n='GroupName'; e={$GroupName}}, @{n='GroupOU'; e={$GroupOU}}, SamAccountName, ObjectClass, DistinguishedName
} | Export-Csv -NoTypeInformation -Path C:\Temp\UKSouthNorth.csv

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Jose Gabriel Ortega CastroCEO Faru Bonon IT - EE Solution ExpertCommented:
And this will be my version. you can see the steps in there.

[CmdletBinding()]
param(
    [Parameter(Mandatory=$true,Position=0)]$OU
)

$SearchedGroup1="UKSouth"
$SearchedGroup2="UKNorth"
$outputFile="out.csv"

#region Functions
function Get-OUDN{
    [Cmdletbinding()]
    param(
        [Parameter(Mandatory=$true,Position=0)]$OuName
    )
    BEGIN{}
    PROCESS{
        $OU = Get-ADOrganizationalUnit -Filter {name -like "ou"}
    }
    END{
        RETURN $OU.DistinguishedName
    }

}
function Load-ADModule{
    [CmdletBinding()]
    [OutputType([bool])]
   
    $Getmd = Get-Module -ListAvailable | Where-Object{ $_.Name -like "ActiveD*"} | Select Name
    [bool]$output=$false

    if( $Getmd.Name -clike "ActiveDirectory"){
		if(! (Get-Module ActiveDirectory)){
			Write-Output "Loading the Active Directory Module"
			Import-Module ActiveDirectory
			Write-Output "Loaded"
		}
		else{
			Write-Output "Active Directory Module for Powershell is already loaded"
		}
        $output= $true
    }
	return $output
}
#endregion


####START SCRIPT
#LOAD AD
if(-not(Load-ADModule)){
    Write-Output "Active Directory Module was not found"
    Write-Output "For this script to run it is required the ActiveDirectory Module, Please run this script in a Windows Server with the Active Directory Module Enabled (or a Domain Controller)"
    exit(0)
}


#Get DN from the main OU
$DN =Get-OUDN $OU

$SearchedOU = Get-ADOrganizationalUnit -SearchBase $DN -Filter {Name -ne $OU}  | select Name,DistinguishedName


$groups=@()
foreach($CurrentOU in $SearchedOU){
    $GDN= $CurrentOU.DistinguishedName
    $group = get-ADGroup -SearchBase  $GDN -Filter  {Name -like $SearchedGroup1 -or Name -like $SearchedGroup2}
    if($group){
        $groups+=new-object psobject -Property @{"OU"=$CurrentOU;"GroupInfo"=$group}
    }
}

$output=@()
foreach($Currentgroup in $groups){
    foreach($itemgroup in $Currentgroup.GroupInfo){
        $Members =Get-ADGroupMember -Identity $itemgroup.DistinguishedName

        if($Members){
            foreach($Member in $Members){
                $output+= New-Object psobject -Property @{"OU"=$Currentgroup.OU.Name;"Group"=$itemgroup.Name;"Member"=$Member.SamAccountNAme;"MemberName"=$Member.Name;"MemberDN"=$Member.DistinguishedName}
            }
            #    $group | Add-Member -MemberType NoteProperty -Name "UsersInCurrentGroup" -Value $Members
        }
    }
    

}


$output | Export-Csv -NoTypeInformation -Path $outputFile

Open in new window

Jay ThomasAuthor Commented:
Thank you very much chaps. I'll try these tomorrowand eport back. Thank you again.
Jay ThomasAuthor Commented:
Thank you for your efforts. Sorry for the late feedback, just not had time to test both scripts. Thank you.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Powershell

From novice to tech pro — start learning today.