28
Feb 2016
Powershell Groups to CSV
Every once in a while I get a request to drop a bunch of groups to excel, and of course we need to grab more than just the members. I usually get the request as provide title, email address, department and company.
This script gives you access to all the attributes you can get off
Get-aduser -Properties *
My source file or $Importfile is an excel CSV – remember to save it as a csv 🙂
So, here we go, the pullgroupmemberlist.ps1. Note that I do a couple of things in here, basically stripping out comma’s, since they’d hurt the csv, checking for nulls, and that sort of stuff.
<#
This script can be used to list group membership from AD
It utilizes the ActiveDirectory module to interface with AD
Gregory V.
#>
Import-Module ActiveDirectory
$MemberList = New-Item -Type file -Force “d:\_Scripts\GroupMembersB.csv”
$Importfile = “D:\_Scripts\GroupMembershipSourceList.csv”
write-host "Starting Group Membership Export from groups listed in $Importfile"
Import-Csv $Importfile | ForEach-Object {
$GName = $_.GroupName
<# Debug #>
write-host "Processing $GName"
$group = Get-ADGroup $GName
$group.Name | Out-File $MemberList -Encoding ASCII -Append
foreach ($member in Get-ADGroupMember $group)
{
if ($member.objectclass -eq "user") {
$UserInfo = (Get-ADUser $member.SamAccountName -Properties *)
$UserEmail = $UserInfo.EmailAddress
$UserName = $UserInfo.DisplayName.Replace(","," ")
<# Check for Null in User Title and store adjusted variable #>
if (!$UserInfo.Title) {
$UserTitle = "-"
}
else {
$UserTitle = $UserInfo.Title.Replace(","," ")
}
<# Check for Null in User Department and store adjusted variable #>
if (!$UserInfo.Department) {
$UserDepartment = "-"
}
else {
$UserDepartment = $UserInfo.Department.Replace(","," ")
}
<# Check for Null in User Company and store adjusted variable #>
if (!$UserInfo.Company) {
$UserCompany = "-"
}
else {
$UserCompany = $UserInfo.Company.Replace(","," ")
}
$RowOut = "$UserName,$UserTitle,$UserEmail,$UserDepartment,$UserCompany"
}
elseif ($member.objectclass -eq "group") {
$Groupname = $member.name.Replace(","," ")
$RowOut = "Notice - Nested Group: $Groupname in this group"
}
elseif ($member.objectclass -eq "computer") {
$Computername = $member.name.Replace(","," ")
$RowOut = "Notice - Computer Account: $Computername in this group"
}
<# Debug
write-host "$RowOut"
#>
$RowOut | Out-File $MemberList -Encoding ASCII -Append
}
$nl = [Environment]::NewLine | Out-File $MemberList -Encoding ASCII -Append
}
write-host "export data written to $MemberList"
Execute the file with the typical powershell ./filename.ps1