I'm working on a PowerShell script to generate a list of shared mailboxes and the users that have access to those mailboxes. However, I'm a bit stuck and need some help. Here's what I currently have:
```powershell
$Users = Get-Mailbox -RecipientTypeDetails UserMailbox | ForEach($User in $Users) {get-mailbox -resultsize unlimited | Get-mailboxpermission -user $user} | Export-CSV -path "C:\Users\user\Desktop\Exportname.csv"
```
Could anyone help me identify what I might be doing wrong?
6 Answers
Why not just get a list of all mailbox permissions that include users who aren’t the default? You could try this:
```powershell
$mailboxes = Get-Mailbox -RecipientTypeDetails UserMailbox
$permissions = ForEach ($mailbox in $mailboxes) {
Get-MailboxPermission -Identity $mailbox.UserPrincipalName | Where-Object user -ne "NT AUTHORITYSELF"
}
$permissions | Export-CSV -path "C:UsersuserDesktopExportname.csv" -NoTypeInformation
```
It looks like there's a mistake with how you're using the `ForEach`. You have a couple of options: either separate the lines or replace `$Users = ` to make it all one line using `ForEach-Object`. Here's a working version:
```powershell
Get-Mailbox -RecipientTypeDetails UserMailbox | ForEach-Object{get-mailbox $_.name | Get-mailboxpermission} | Export-CSV -path "C:UsersDesktopExportname.csv"
```
Just a suggestion: Instead of treating individual users, consider managing access through groups. I like to create two groups for each mailbox, one for those who can read and edit, and another that can also send emails as the mailbox. The only downside is these groups won't automap in Outlook.
Looks like you have a simple issue with the `ForEach` command. You can separate the commands like this:
```powershell
$Users = Get-Mailbox -RecipientTypeDetails UserMailbox
$Result = ForEach ($User in $Users) {
Get-Mailbox -resultsize unlimited | Get-mailboxPermission -user $user
}
$Result | Export-CSV -path "C:UsersuserDesktopExportname.csv"
```
This way, you're keeping everything organized. You can also export to different file formats if needed!
Your approach seems a bit convoluted. You might want to simplify it like this:
```powershell
Get-Mailbox -ResultSize Unlimited | Get-MailboxPermission | Select-Object Identity, User, AccessRights | Where-Object { $_.User -like '*@*' } | Export-Csv -Path C:Tempmailbox_delegates.csv -NoTypeInformation
```
This should give you a clean CSV file with access details for all mailboxes!
Wouldn't it be better to specifically filter for shared mailboxes rather than user mailboxes? Just pipe it through to `Get-MailboxPermission` for better results.

Related Questions
How To: Running Codex CLI on Windows with Azure OpenAI
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically