Putting E3 users on lithold

So each week I want to run a scheduled task that will get all the E3 users and if they don’t have litigationholdenabled set, then set it.

Here’s my code:

$users= Get-MsolUser -all | ?{$_.licenses[0].accountskuId -match 'amkor:ENTERPRISEPACK'}

$users | ForEach {get-mailbox -Identity $_.userprincipalname |? {$_.litigationholdenabled -ne $true} |set-mailbox -LitigationHoldEnabled $true -LitigationHoldDuration 1825 }

Now the first line gets processed pretty quick (5900 users), but the second line takes about 40 minutes (under 20 users each week that don’t have this enabled). I get that I’m doing a foreach so it has to go through each one, but I don’t know another way . Is there a different way to re-write this so it doesn’t take as long or am I just being impatient?

It the $user variable contains ~5900 users then your second line has to do a get-mailbox on each of the those users. You will need to find a way to filter out the users with the litigationholdenabled from the as closer to the beginning (or left side) of the pipeline to speed things up.
I not not have an exchange lab so I can only offer you theory.

backwards.

try using get-mailbox -filter “litigationhold -eq ‘false’” #may require where statement

foreach mailbox user…

if ((Get-MsolUser $user).licenses[0].accountskuId -eq ‘amkor:ENTERPRISEPACK’){

set-mailbox…

}

This way you’re only working with the non-litigation users only and not looping through all 5900.

Thank you for your suggestions; it gives me more ideas on how to resolve this.

I get that it’s backwards, but I failed to mention that we have 5000 K1/E1 users that it would result in $users if I did the:

$users = get-mailbox -filter litigationholdenabled -eq $false

Also, litholds can only be placed on E3 users. I don’t think there is going to be a quick way to do this or I just have to figure out something else that can reduce the number.

If I figure it out, I’ll post it.

Welcome to the cloud… MSOL isn’t very flexible. I actually setup a sql db as a frontend to make changes in the cloud. I have all my user info in the db and a lastmodified column in all tables. I have a script that runs every 15 minutes pulling the users lastmodified since the previous run and apply the changes to the cloud.