Script for removing O365 licenses from a user

Hello,
powershell/sysadmin beginner here, im trying to automate the process when an employee leaves a company from an IT perspective - disabling the AD account, moving it into a different OU, removing licenses, removing group memberhsip.

Im trying to fit this into a single powershell script, disabling the AD account and moving it was easy but im running into trouble when trying to remove licenses.
My idea was getting all the assigned licenses and looping it with a foreach command.
What i basically have right now is this:
$givemelicenses = get-msoluser -userprincipalname testuser@domain.com | select-object licenses
output of this is :

i was thinking the next logical step would be this:
foreach ($licenses in $givemelicenses) {Set-MsolUserLicense -UserPrincipalName testuser@domain.com -removelicenses $licences}

the cmdlet is processed but when i run the previos variable or check the O365 tenant i see the licenses are still applied to the user.
Any idea where im going wrong?
thanks

It might not be a direct answer to your question but it might make your life easier anyway.

I’d recommend to assign licenses using AD group memberships. This way you just need to remove the user from the according security groups and don’t have to worry about the rest anymore. :wink:

1 Like

Was just writing a similar answer to what Olaf proposed.

Also when you use a cloud-synced AD-group for licensing you probably don’t need to mix AAD and AD commands in your script for disabling users as you remove the user from the local AD-group and on next sync it will automagically remove the user from the cloud-group and remove the license.

1 Like

Thank you for the suggestions but i dont want to go around redesigning the system as it is, i would preferably get this script to work :slight_smile:
I’ve made “some” headway, i did this:
$info = get-msoluser -userprincipalname testuser@domain.com
$info.licenses.accountskuid
I get this:
image

So i would just need to store this output as 2 separate values in an array which i can then process with foreach/set-msoluser combination.
Because if i manually do this:
set-msoluserlicense -userprincipalname testuser@domain.com -removelicenses reseller-account:ATP_ENTERPRISE
The above cmd does in fact remove the said license, so i would just need to loop it for each value of the previous result.
Any advice?
Thanks

EDIT: i solved it. thanks anyway

Yes. Do not choose the cheap and low quality hobby solution. Make it proper to have less work next time. :wink: