I’m a PowerShell newbie with a question about shortening some cmdlets I ran recently in Office 365. I converted some mailboxes to Shared Mailboxes, 9 in total. I then had to add 5 users to each of the 9 mailboxes. Since at the moment I am only good at one liners, I ended up doing the following and running it in PowerShell ISE…
Add-MailboxPermission -Identity smb1@email.com -User user1 -AccessRights FullAccess -InheritanceType All
Add-MailboxPermission -Identity smb1@email.com -User user2 -AccessRights FullAccess -InheritanceType All
Add-MailboxPermission -Identity smb1@email.com -User user3 -AccessRights FullAccess -InheritanceType All
Add-MailboxPermission -Identity smb1@email.com -User user4 -AccessRights FullAccess -InheritanceType All
Add-MailboxPermission -Identity smb1@email.com -User user5 -AccessRights FullAccess -InheritanceType All
Add-MailboxPermission -Identity smb2@email.com -User user1 -AccessRights FullAccess -InheritanceType All
Add-MailboxPermission -Identity smb2@email.com -User user2 -AccessRights FullAccess -InheritanceType All
Add-MailboxPermission -Identity smb2@email.com -User user3 -AccessRights FullAccess -InheritanceType All
Add-MailboxPermission -Identity smb2@email.com -User user4 -AccessRights FullAccess -InheritanceType All
Add-MailboxPermission -Identity smb2@email.com -User user5 -AccessRights FullAccess -InheritanceType All
You get the idea. Did this for 7 other mailboxes. It ran fine of course but curious to know how I could shorten this since I know I’ll probably have to do this again in the future.
Looks like you could do a nested loop, too. Probably better to use the keyword foreach loop for nested loops.
Something along these lines:
$UserList = 'user1', 'user2' # etc
$EmailList = 'smb1@email.com', 'smb2@email.com' # etc
# Bonus: splatting!
$Params = @{
AccessRights = "FullAccess"
InheritanceType = "All"
}
foreach ($Email in $EmailList) {
# Add/overwrite the email parameter
$Params['Identity'] = $Email
foreach ($User in $UserList) {
# Add/overwrite in the user parameters
$Params['User'] = $User
Add-MailboxPermission @Params
}
}
Now, in this instance it’s probably shorter without the splatting and just throwing all those parameters on the command call directly as you have it, but in my opinion it is a little tidier to do the splat.
Always check Get-Help or Get-Command -Syntax and see what the parameter types are. If you see someType then it permits arrays of items, but if you see someType it does not.
Both those displays have types in angle brackets, which apparently aren’t allowed even in safe forms on this forum. sigh