I want to create a full mailbox permission report and export it to a CSV in PowerShell.
$report = @()
$mailboxes = Get-Mailbox -ResultSize unlimited -RecipientTypeDetails sharedmailbox
foreach ($mailbox in $mailboxes)
{
$permissions = Get-Mailbox $mailbox.PrimarySmtpAddress | Get-MailboxPermission | Select-Object user, accessrights
$users = $permissions.user
$accessRights = $permissions.accessrights
$sendAsPermissions = Get-Mailbox $mailbox.PrimarySmtpAddress | Get-ADPermission | Where-Object {$_.extendedrights -eq "send-as"} | select -ExpandProperty user
$sendOnBehalfPermissions = Get-Mailbox $mailbox.PrimarySmtpAddress | select -ExpandProperty grantsendonbehalfto
$properties = @{
Identity = $mailbox.PrimarySmtpAddress
Users = ($permissions.user -join "`n")
AccessRights = ($permissions.accessrights -join "`n")
SendAs = ($sendAsPermissions -join "`n")
SendOnBehalf = ($sendOnBehalfPermissions -join "`n")
}
$mailboxObject = New-Object -TypeName psobject -Property $properties
#$mailboxObject | select identity, users, accessrights | Export-Csv -Append -NoTypeInformation -Path c:\temp\test.csv
$mailboxObject | select identity, users, accessrights, sendas, sendonbehalf | out-gridview
}
The gridview shows exactly what I want but I'm having a hard time getting it correctly exported to a CSV.
I know for a fact this could be both better and more suited to your exact case, but figured it was still worth sharing.
You can get the
Import-Excel
module which easily allows you to create and format Excel files. You may install it from the Powershell Gallery located here. This is basically assuming that your sheets are for human eyes only, and given the format, I think I can say with some degree of confidence that is true.First I started by collecting all the objects before appending, which I think is a pretty common mistake. Just output the object directly and collect it in a variable.
Now I'm going to use the
Export-Excel
cmdlet to generate a OfficeOpenXml.ExcelPackage object, which we can then manipulate with a few helper functions. I found that this almost emulatedOut-Gridview
. The header wrapping is just a little bit off, but you're welcome to experiment with different parameters until you find something that looks exactly right to you.