-
Notifications
You must be signed in to change notification settings - Fork 1
/
o365_group_export.ps1
67 lines (46 loc) · 2.1 KB
/
o365_group_export.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<#
.SYNOPSIS
Powershell script to export all distribution groups and user memberships to a nice CSV for HR!
Author: London Crosby
Created: <09-26-2018>
#>
$O365Creds = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/Powershell -Credential $O365Creds -AllowRedirection -Authentication basic
Import-PSSession $Session -AllowClobber
$Outputfile = Read-Host "Enter export path and filename, ie: C:\Users\londonc\Desktop\O365_groups.csv"
# Get all email distribution groups
$Groups = Get-DistributionGroup -ResultSize 5000
# Get all mail users, including contacts.
$Users = Get-MailContact -ResultSize 5000
# Build list of all groups based on PrimarySmtpAddress since using GUID for later queries doesn't seem to work right.
$GroupColumn = New-Object Collections.generic.list[object]
ForEach ($i in $Groups) {
$GroupColumn.Add("$($i.PrimarySmtpAddress)")
}
# Declare to hold all the data
$Table = @()
# Iterate through every mail user
ForEach ($User in $Users) {
$UserEmail = $User.PrimarySmtpAddress
# Make object to hold each row of data to be exported
$ObjRow = New-Object PSObject
$ObjRow | Add-Member -MemberType NoteProperty -Name "SMTP" -Value $UserEmail
$ObjRow | Add-Member -MemberType NoteProperty -Name "DisplayName" -Value $($User.DisplayName)
$ObjRow | Add-Member -MemberType NoteProperty -Name "RecipientType" -Value $($User.RecipientType)
# Query each group for it's members
ForEach ($Group in $GroupColumn) {
$GroupMembers = Get-DistributionGroupMember -Identity $Group
# Find if user is in the group or not
If($($GroupMembers.PrimarySmtpAddress) -contains "$UserEmail") {
$IsMember = "true"
}else{
$IsMember = "false"
}
$ObjRow | Add-Member -MemberType NoteProperty -Name $Group -Value $IsMember
}
$Table += $ObjRow
# Build CSV line by line. This way if something fails you still have saved results.
$Table | Export-Csv -Path $OutputFile -Append -NoTypeInformation
}
# Clean up
Remove-PSSession $Session