Author Posts

July 14, 2016 at 6:21 pm

The topic made sense in my head before I typed it...

On a scale of 1-10, I'm about a 3 with Powershell (more than a beginner, but less than intermediate).

I have a rudimentary script which dumps ADGroupMembers to CSV and looks something like this:

Get-ADGroupMember "Late Shift" | Select distinguishedName | Export-Csv "c:\reports\LateShift.csv" -NoTypeInformation
Get-ADGroupMember "Mid Shift" | Select distinguishedName | Export-Csv "c:\reports\MidShift.csv" -NoTypeInformation
Get-ADGroupMember "Early Shift" | Select distinguishedName | Export-Csv "c:\reports\EarlyShift.csv" -NoTypeInformation

(This is only an example. My actual script runs one line for each of 60 groups.)

I've since created a new group which contains the other groups. Let's call it "Shifts".

When I run

Get-ADGroupMember Shifts | Select Name

, I get a list of the other groups. I'd like to loop through that list and get the memberlist of those groups. I started with this:

$Group = Get-ADGroupMember Shifts | Select Name

foreach ($Name in $Group) {
    Write-Host "Processing" $Name
}

The output:

Processing @{Name=Early Shift}
Processing @{Name=Late Shift}
Processing @{Name=Mid Shift}

What should I be doing to get the correct group name passed through the loop?

Thx!

Robb

July 14, 2016 at 7:19 pm

Select -ExpandProperty name

I think that is what you are after. Select-Object just limits the properties of the objects and doesn't extract the information, so you end up with an object with one property. -ExpandProperty pulls the string out of the object's property.

Alternatively you could do this inside the script:

Write-Host "Processing" $Name.Name
  • This reply was modified 2 years, 1 month ago by  Craig Duff.

July 14, 2016 at 8:41 pm

Thanks, Craig! Here's what I ended up with:

#Clear the previous contents from the folder.
Remove-Item C:\Reports\*.*

#Get the group members from the Shifts security group.
#The Shifts security group contains other security groups.
$Group = Get-ADGroupMember Shifts | Select -ExpandProperty Name

#Dump the members of the groups contained in Shifts to separate CSV files.
foreach ($Name in $Group) {
    $CSVFile = "C:\Reports\"+$Name+".csv"
    Get-ADGroupMember $Name |
        Select DistinguishedName | Sort DistinguishedName |
            Export-Csv $CSVFile -NoTypeInformation
}

#Not required, but I wanted to know how many files to expect,
#as well as when the script finished.
Write-Host
Write-Host "Total processed:" $Group.Count
Write-Host "Done."

I went from 62 lines to 14 (not including #s)!