Script goal: Get user mailbox properties and export each value of the ‘EmailAddresses’ property array to its own cell in a csv.
This is one of my first experiences working with custom psobjects and property arrays so naturally I came across a ton of road blocks on the road to getting this to work. It was quite the arduous experience getting these the values of a property array into their own cells in a csv. My question is, if anyone has come across this need in their environment, how have you solved it and please notify me if it would appear I am not taking advantage of something powershell has got to offer.
$mailboxes = Get-Mailbox | Select-Object Name, Identity, RecipientTypeDetails, EmailAddresses -First 20
$modArray = @()
$emailCount = @()
Foreach ($a in $mailboxes) {
# Regex = Exclude any item that matches 'smtp/SMTP'
[regex]$regex = "^(?i)smtp"
# Convert $a.Emailaddresses to an Array list to circumvent "collection was of a fixed size" error
[System.Collections.ArrayList]$arrayList = $a.EmailAddresses
# Find emails in $arrayList that dont start with smtp/SMTP and stores them in $remEmails
$remEmails = $arrayList | Where-Object {$_ -notmatch $regex}
# iterate through $arrayList items for removal from array
For ($i = 0; $i -lt $remEmails.Count; $i++) {
If ($remEmails.Count -gt 1) {
$arrayList.Remove($remEmails[$i])
}
Else {
$arrayList.Remove($remEmails)
}
}
# Add $a into $modArray with its new $a.EmailAddresses values
$modArray += $a
# Store email address count of each mailbox. See more info in comment above $count var
$emailCount += $a.EmailAddresses.Count
}
# Find the largest number in the $emailCount array
# This is used to set the value for the amount of additional properties to add to the psObject
# Not desireable but necessary to be able to export-csv all the properties
$count = $emailCount | Measure-Object -Maximum | Select-Object -ExpandProperty Maximum
$result = @()
ForEach ($m in $modArray) {
# Create new psObject. [ordered] was a life saver because hashtables dont retain property order.
$obj = New-Object psobject -Property ([ordered]@{
Name = $m.Name
Identity = $m.Identity
Mailtype = $m.RecipientTypeDetails
Email = $m.EmailAddresses | Where-Object {$_ -clike "SMTP:*"}
})
# Create new alias properties based on the number stored in $count variable
For ($i = 0; $i -lt $count; $i++) {
$obj | Add-Member -MemberType NoteProperty -Name "Alias_$i" -Value $null
}
# Adding the values to the Alias properties
If ($m.EmailAddresses.Count -gt 1) {
$addr = $m.EmailAddresses -cnotlike "SMTP:*"
For ($i = 0; $i -lt $addr.Count; $i++) {
$addrValue = "Alias_$i"
$obj.$addrValue = $addr[$i]
}
}
Else {
$obj = New-Object psobject -Property ([ordered] @{
Name = $m.Name
Identity = $m.Identity
Mailtype = $m.RecipientTypeDetails
Email = $m.EmailAddresses | Where-Object {$_ -clike "SMTP:*"}
})
}
# Add $obj to $result array
$result += $obj
$obj = $null
}
$result | Export-Csv $env:USERPROFILE\Desktop\Users.csv -NoTypeInformation