idarryl
idarryl

Reputation: 769

More efficient foreach-object loop in Set-MailboxFolderPersission?

I wrote this script that applies Exchange calendar reviewer permissions for everyone in a group, to everyone else in that group. It works, but it's a little slow. I wondered if anyone could suggest anyway to improve the efficiency of the loop?

$ADgroup = Get-ADGroupMember -Identity "My Group"

    $ADgroup | foreach-object 
{
    $mb = Get-Mailbox -identity $_.SamAccountName
    foreach ($person in $ADgroup)
        {if ($person.objectGUID -ne $mb.Guid)
            {
            $name = $person.SamAccountName
            Add-MailboxFolderPermission -Identity "${name}:\Calendar" -User $mb.Alias -AccessRights Reviewer
            }
        }
}

Thanks in advance 

Upvotes: 1

Views: 789

Answers (1)

Jaigene Kang
Jaigene Kang

Reputation: 164

If you have the requirements for Powershell Workflow you can use it to run the tasks in parallel (namely the inner foreach). There's also jobs, but they're a bit more of a pain.

To benefit though, you'd probably have to restructure your logic to something like:

workflow {
    param($samsToAdd)

    foreach -parallel($samToAdd in $samsToAdd) {
        sequence{
                $name = $samToAdd.name
                $mb = $samToAdd.mb
                Add-MailboxFolderPermission -Identity "${name}:\Calendar" -User $mb.Alias -AccessRights Reviewer
            }
        }
    }
}

$ADgroup = Get-ADGroupMember -Identity "My Group"

$samsToAdd = @()
$ADgroup | foreach-object 
{
    $mb = Get-Mailbox -identity $_.SamAccountName
    foreach ($person in $ADgroup)
        {if ($person.objectGUID -ne $mb.Guid)
            {
                $name = $person.SamAccountName
                $samsToAdd += new-object psobject -property @{
                    name = $name
                    mb = $mb
                }
            }
        }
}

I'd also comment that the permissions being added is somewhat of a slow task based on the iterative nature. So, parallel operations will only gain you so much, but IMO it will always be somewhat slow.

Upvotes: 1

Related Questions