How to Use PowerShell to Automatically Assign Licenses to Your Office 365 Users - TechNet Articles - United States (English) (2022)

#script to assign or swap the licenses of a user

#Copyright Microsoft @ 2012

#DISCLAIMER

#The sample scripts are not supported under any Microsoft standard support program or service.

#The sample scripts are provided AS IS without warranty of any kind.

#Microsoft further disclaims all implied warranties including, without limitation,

#any implied warranties of merchantability or of fitness for a particular purpose.

#The entire risk arising out of the use or performance of the sample scripts and documentation remains with you.

#In no event shall Microsoft, its authors, or anyone else involved in the creation, production,

#or delivery of the scripts be liable for any damages whatsoever (including, without limitation,

#damages for loss of business profits, business interruption, loss of business information,

#or other pecuniary loss) arising out of the use of or inability to use the sample scripts or documentation,

#even if Microsoft has been advised of the possibility of such damages.

# Setup the UI Colors

$host.ui.RawUI.ForegroundColor = "White"

$host.ui.RawUI.BackgroundColor = "Black"

# change the username to a admin account in your tenant i.e. admin@contos.onmicrosoft.com

$Username="usernotset"

# to set a new password delete this script and run SetupScript.ps1 again.

$pass="passnotset"

### added 20140515-timbos

#In order to assign a license a user needs to have a UsageLocation defined in Office 365

# By default this script will set the UsageLocation to the country attribute ("c" in AD) defined for the user

# if this attribute is not configured the following default UsageLocation will be assumed

# to set a new default Usagelocation change the folling

$DefaultUsageLocation ="usagelocationnotset"

###

# check if the password and user are set to something

if(($pass -contains "notset")-or($Username -contains "notset"))

{

"You need to set your username and/or create an encrypted password for the admin account specified in this script before continuing."

Exit 2

}

# Global Variables

<#---------Logfile Info----------#>

# setup the logfile

$script:logfile = ".\Logs\AssignLicense-$(get-date -format MMddyyHHmmss).log"

$script:Seperator = $("-" * 25)

$script:loginitialized = $false

$script:FileHeader = "***Application Information***"

# Global Functions

function write-log([string]$info)

{

# verify the Log is setup and if not create the file

if($script:loginitialized -eq $false)

{

$FileHeader > $logfile

$script:loginitialized = $True

}

$info = $(get-date).ToString()+": "+$info

$info >> $script:logfile

}

# setup the eventlog source if it does not exist

New-EventLog -LogName Application -Source O365LicenseUpdate -ErrorAction SilentlyContinue > Out-Null

(Video) Enabling and Managing Microsoft Office 365

# write the start event to the eventlog

write-Eventlog -logname Application -Entrytype information -EventId 0 -source O365LicenseUpdate -message 'The O365 License Update AssignLicense has been started'

# load the MSOnline PowerShell Module

# verify that the MSOnline module is installed and import into current powershell session

If (!([System.IO.File]::Exists(("{0}\modules\msonline\Microsoft.Online.Administration.Automation.PSModule.dll" -f $pshome))))

{

Write-EventLog -LogName Application -EntryType Error -EventId 99 -Source O365LicenseUpdate -Message "The Microsoft Online Services Module for PowerShell is not installed. The Script cannot continue."

write-log "Please download and install the Microsoft Online Services Module."

Exit 99

}

$getModuleResults = Get-Module

If (!$getModuleResults) {Import-Module MSOnline -ErrorAction SilentlyContinue}

Else {$getModuleResults | ForEach-Object {If (!($_.Name -eq "MSOnline")){Import-Module MSOnline -ErrorAction SilentlyContinue}}}

write-Eventlog -logname Application -Entrytype information -EventId 0 -source O365LicenseUpdate -message 'MSOnline module imported'

# create the password from the encrypted string and setup the credential object

$password = ConvertTo-SecureString $pass

$cred = New-Object -typename System.Management.Automation.PSCredential -argumentlist $Username,$password

$ErrHandle = ""

# Connect to Microsoft Online Service

Connect-MsolService -Credential $cred # -errorAction silentlyContinue -errorvariable $Errhandle

if ($ErrHandle -ne ""){

# handle any logon errors

$message6 = 'Could not log on O365 with ' + $($Username) + ' to update licenses. ' + $ErrHandle

write-Eventlog -logname Application -Entrytype error -EventId 6 -source O365LicenseUpdate -message $message6

exit

}

else {

write-Eventlog -logname Application -Entrytype information -EventId 0 -source O365LicenseUpdate -message 'Logged In'

}

# setup the user info

$script:UseInfo = $($(get-date -format HH:mm:ss) + "`t" + $env:username + "`t")

# get the company prefix for the license packages

$licenseList=Get-MsolAccountSku

if(($licenseList.GetType().Name) -eq "AccountSkuDetails") {

$licensePrefix =$licenseList.AccountSkuId.Split(":")[0]

}

else{

$licensePrefix =$licenseList[0].AccountSkuId.Split(":")[0]

}

Trap [Exception] {

# Something bad happened let's dump it into the log file

write-log $("$UseInfo`t$_. - Line:(" + $($_.InvocationInfo.ScriptLineNUmber)+":"+$($_.InvocationInfo.OffsetInLine)+ ") " + $($_.InvocationInfo.Line))

continue

}

# Main Loop starts here

$csvfile = ''

# Get the list of all CSV Files

###changed 20140515

$filecol = Get-childitem -path .\queuedLicense | Where-Object {$_.Extension -eq '.csv'}

if($filecol -ne $null){

# iterate through the list of files and execute on every user in each file

foreach ($file in $filecol) {

$csvfile = $file.FullName

Write-host "Processing "$csvfile

$Users = import-csv $csvfile -Delimiter ";"

(Video) Office 365 Support Administration Basics | New IT Professionals

$Message7 = 'Start processing license file ' + $csvfile

write-Eventlog -logname Application -Entrytype information -EventId 0 -source O365LicenseUpdate -message $Message7

write-log $Message7

$UPN = ''

# iterate through the users in the file

foreach ($user in $users) {

# make sure the user has a license and a UPN in the row. If not skip the user

if (( $user.O365LicenseType -ne "") -and ($user.userPrincipalName -ne "")){

$ErrHandle = ""

$NewLicenseExc = ""

$OldLicenseExc = ""

$O365LicenseType = $licensePrefix + ":" + $user.O365LicenseType.trim()

$UPN = $user.userPrincipalName.Trim()

#added 20140515-timbos

if ($user.UsageLocation -ne "") {

$UsageLocation = $user.UsageLocation

}

else {

$UsageLocation = $DefaultUsageLocation

}

###

$message1 = 'Update user license for user: ' + $UPN + ', this can take 15 minutes to become effective'

$message2 = 'license for user ' + $UPN + ' is added in O365'

$message3 = 'Wrong Licence type for user: ' + $UPN + ' in AD'

$message4 = 'License stays the same for user: ' + $UPN

$message5 = 'Error file ' + $csvfile +' empty or user not found in O365: ' + $UPN

$message6 = 'User or License Record were empty. Skipped.'

$setLicenseOptions = $false

$skipUser =$false

write-host $UPN , $O365LicenseType

# Apply Licenses as needed

# Check if we need to create LicenseOptions

# Using the pipe (|) symbol as a delimter because some service plans do contain an underscore (_) character

if($O365LicenseType.Contains("|")) {

# Split the Options into an Array

$licenseOptions = $O365LicenseType.Split("|")

# Pick the first Option as the AccountSkuID

$O365LicenseType = $licenseOptions[0]

# Create an empty Array for the disabledPlans Object

$lo=@()

for($i=1;$i -le $licenseOptions.Count;$i+=1) {

# Make sure we only add non-null disabledPlans to the new Array

if($licenseOptions[$i] -ne $null) {

$lo+=$licenseOptions[$i]

}

}

# Create the LicenseOptions Object

$licenseOptionObject = New-MsolLicenseOptions -AccountSkuId $O365LicenseType -DisabledPlans $lo

$setLicenseOptions = $true

}

# Check if user exists in Office 365

Try {

$userObject = Get-MsolUser -UserPrincipalName $UPN -erroraction stop

###added 20140515-timbos

if (!$userObject.UsageLocation) {

(Video) Microsoft 365 Virtual Marathon - Microsoft365DSC, The next best thing since sliced bread

Set-MsolUser -UserPrincipalName $UPN -UsageLocation $UsageLocation

}

###

if ($userObject.islicensed) {

$OldLicenseExc=$userObject.Licenses[0].AccountSkuID

foreach($license in $userObject.Licenses) {

# check if the user has already the same license package set

if($license.AccountSkuID -eq $O365LicenseType) {

# The user has the same License Package. To avoid Dataloss we will Skip this user

$skipUser=$true

}

}

}

}

Catch {

# Something went wrong log it

write-Eventlog -logname Application -Entrytype warning -EventId 5 -source O365LicenseUpdate -message $message5

write-host -foregroundcolor red $message5 ' ' $UPN

write-log $message5 $UPN

}

# if the user has a license that is not equal to the new license switch it out

if (!$skipUser) {

$NewLicenseExc = $O365LicenseType

$ErrHandle = ""

Try {

$userObject=Get-MsolUser -UserPrincipalName $UPN -erroraction stop

if (!$userObject.isLicensed) {

if($setLicenseOptions -eq $true) {

Set-MsolUserLicense -UserPrincipalName $UPN -AddLicenses $NewLicenseExc -LicenseOptions $licenseOptionObject -ErrorVariable $ErrHandle

}

else {

Set-MsolUserLicense -UserPrincipalName $UPN -AddLicenses $NewLicenseExc #-ErrorVariable $ErrHandle

}

# we added a new license for the user

write-Eventlog -logname Application -Entrytype information -EventId 2 -source O365LicenseUpdate -message $message2

write-log $message2

write-host 'A new license is set for user ' $UPN

}

elseIf (!$skipUser) {

if(!($NewLicenseExc -eq $OldLicenseExc)) {

if($setLicenseOptions -eq $true) {

Set-MsolUserLicense -UserPrincipalName $UPN -RemoveLicenses $OldLicenseExc -AddLicenses $NewLicenseExc -LicenseOptions $licenseOptionObject -ErrorVariable $ErrHandle

$setLicenseOptions=$false

}

else {

Set-MsolUserLicense -UserPrincipalName $UPN -RemoveLicenses $OldLicenseExc -AddLicenses $NewLicenseExc -ErrorVariable $ErrHandle

}

}

# We have updated the license of the user

write-Eventlog -logname Application -Entrytype warning -EventId 1 -source O365LicenseUpdate -message $message1

Write-Host $message1

write-log $message1

}

else

{

(Video) #office365 Masterclass: How and when to use the 27 apps in #microsoft365 - 2022 update

# the license was the same before and after, nothing has changed

write-Eventlog -logname Application -Entrytype information -EventId 4 -source O365LicenseUpdate -message $message4

Write-Host $message4

write-log $message4

}

$setLicenseOptions=$false

$skipUser=$false

}

catch{

# Something went wrong log it

write-Eventlog -logname Application -Entrytype warning -EventId 5 -source O365LicenseUpdate -message $message5" "$ErrHandle

write-host -foregroundcolor red 'File is empty or could not find user ' $ErrHandle

write-log $message5 ' ' $ErrHandle

$setLicenseOptions=$false

$skipUser=$false

}

}

else {

# the license was the same before and after, nothing has changed

write-Eventlog -logname Application -Entrytype warning -EventId 4 -source O365LicenseUpdate -message $message4

write-host -foregroundcolor red $message4 + " " + $UPN

write-log $message4 ' ' $UPN

$setLicenseOptions=$false

}

}

else {

# One of the fields in the CSV file was not valid for setting up a license for the user

write-Eventlog -logname Application -Entrytype warning -EventId 6 -source O365LicenseUpdate -message $message6

write-host -foregroundcolor red $message6 ' ' $UPN

write-log $message6 ' ' $UPN

$setLicenseOptions=$false

}

}

# Belongs to foreach *.csv

Try {

# move the file to the completedImportFiles Folder

move-item -path $csvfile -destination .\completedImportFiles -ErrorVariable $ErrMsg

}

Catch {

# Something went wrong log it

write-Eventlog -logname Application -Entrytype warning -EventId 5 -source O365LicenseUpdate -message 'Could not move the file '$ErrMSG

write-log "Could not move the file" $ErrMsg

}

}

}

else {

# We have no file to process

write-Eventlog -logname Application -Entrytype information -EventId 0 -source O365LicenseUpdate -message 'No queued license import file found.'

write-log "No queued license import file found."

}

# Log All Done Message

write-Eventlog -logname Application -Entrytype information -EventId 0 -source O365LicenseUpdate -message 'The O365 License Update AssignLicense has been ended'

write-log "License Update completed."

write-log "==========================================================================="

Write-Host "License Update completed."

(Video) Skype Academy: Meetings

FAQs

How do I bulk assign licenses in Office 365 PowerShell? ›

How to: Bulk assign Office 365 licenses with PowerShell
  1. Step 1: Install MS Office 365 Sign On Assistant. http://www.microsoft.com/en-us/download/details.aspx? ...
  2. Step 2: Install Azure AD PowerShell Module. ...
  3. Step 3: Find PowerShell and Right-Click Run As ISE. ...
  4. Step 4: Create the CSV file. ...
  5. Step 5: PowerShell Script. ...
  6. Step 6: Prompts.
Dec 18, 2015

How do I automatically assign a license in Office 365? ›

Office 365 Group Based Licensing
  1. Open Groups. You can find it under Azure Active Directory on the left side and then Groups.
  2. Open your new Group and select Licenses. ...
  3. Select Assignments to assign a new license.
  4. Select the license you want to assign to the Group. ...
  5. License are assigned.
Feb 11, 2021

How do I bulk assign licenses in Office 365? ›

Assign licenses to multiple users

At the top, select Manage product licenses. In the Manage product licenses pane, select Assign more: Keep the existing licenses and assign more > Next. Under Licenses, select the box for the license(s) that you want the selected users to have.

How do I change my Office 365 license using PowerShell? ›

Select Office 365 -> License Management ->Assign/Remove licenses . Select Replace licenses option, choose the desired license(s), and User Location from the drop down list. Choose the Office 365 account and its users, and click Apply.

How do I connect Office 365 to PowerShell? ›

Connecting to Office 365(Exchange Online) via Powershell
  1. Open Powershell as administrator.
  2. Run command – Set-ExecutionPolicy Remotesigned.
  3. Type Y for yes.
  4. Run command – $UserCredential = Get-Credential.
  5. Sign in with O365 administrator account (user@company.com)
  6. Run command – Import-PSSession $Session.

How do I find my PowerShell license for Office 365? ›

Instead of logging into the Office 365 portal and using a filtered view in the admin center, you can do it straight from the command line.
  1. Connect to Office 365 via Powershell. ...
  2. Run Get-MsolAccountSku to get a list of the current licenses in your Office 365 tenant.

How do I assign a license to Active Directory? ›

On the Products page, select the name of the license plan you want to assign to the user. On the Azure Active Directory Premium Plan 2 page, select Assign. On the Assign page, select Users and groups, and then search for and select the group you're assigning the license.

How can you add more licenses in the Office 365 tenant? ›

In the admin center, go to the Billing > Your products page.
  1. On the Products tab, select the subscription to which you want to add licenses.
  2. On the subscription details page, in the Licenses section, select Add more licenses.
  3. In the Add more licenses pane, select Use a new and unused product key, then select Next.
Aug 18, 2022

How do group assigned licenses show up for individual users? ›

Go to Azure Active Directory > Groups, and find the group that licenses were assigned to. On the group page, select Licenses. The notification on top of the page shows that there are 10 users that licenses couldn't be assigned to. Open it to see a list of all users in a licensing error state for this group.

How do I Manage my Microsoft Office license? ›

In the Microsoft 365 admin center, go to the Billing > Licenses page. On the Licenses page, choose Microsoft 365 Apps for Education (device) or Microsoft 365 Apps for enterprise (device). On the next page, choose a subscription, then choose Assign licenses.

Which option can be used to add a new domain to your Office 365 tenant? ›

In the Microsoft 365 admin center, choose Setup. Under Get your custom domain set up, select View > Manage > Add domain. Enter the new domain name that you want to add, and then select Next. Sign in to your domain registrar, and then select Next.

What are the different Office 365 Licenses? ›

There are three main O365 suites: Business, Enterprise, and frontline workers. Within the Business Suite, 3 plans are available: Basic, Standard, and Premium. The Standard plan doesn't include an Office client but has email and Yammer. Premium gives advanced analytics and security.

How do I get a list of licensed users in Office 365 PowerShell? ›

Use the Azure Active Directory PowerShell for Graph module

First, connect to your Microsoft 365 tenant. To list all of the users in your subscription, use the Get-AzureAdUser -All $true command.

Where are the accounts assigned licenses for individual Office 365 applications? ›

The admin center tells you what licenses you have, the licenses assigned and available, and the accounts with assigned licenses. You can export lists of users with a selected license to a CSV file for reporting purposes or to import into Power BI for analysis.

What is SKUAssigned? ›

SKUAssigned : True

The presence of the ExchangeGUID and license has signified to the provisioning process that a mailbox object should not be provisioned. This test has concluded as expected.

How do I run a PowerShell script? ›

You can also first start Windows PowerShell:
  1. Right-click on the start menu (or press Windows key + X)
  2. Choose Windows PowerShell.
  3. Navigate to the folder where the script is located. cd c:\path\to\script <enter>
  4. Run the PowerShell script. .\PowerShellExampleScript.ps1 <enter>
Dec 21, 2021

How do I link my Office 365 MFA to PowerShell? ›

Step1: Install Exchange Online PowerShell Module for MFA
  1. Login to Exchange Admin Center using Internet Explorer or Edge.
  2. 2.In the EAC, go to Hybrid and click the Configure button (as mentioned in below image) to download the Exchange Online PowerShell Module for MFA. ...
  3. Click Install.
Apr 17, 2019

How do I run Exchange PowerShell? ›

How to Open an Exchange PowerShell
  1. Open PowerShell and enter the following command: $LiveCred = Get-Credential.
  2. Enter the login credentials for Exchange when the window appears, and then click "OK."
  3. Enter the following command once the previous command has processed: Remove-PSSession $Session.

How do I export Office 365 users list with Licenses? ›

How to export all customers' Office 365 users and license details to CSV
  1. Copy and paste the code at the bottom of this page into Visual Studio Code.
  2. Save it as a PowerShell (ps1) file. ...
  3. Press F5 to run the script.
  4. Enter the credentials of an Office 365 Delegated Admin.
  5. Wait for it to complete.

How do I export a list of licensed Office 365 users to a CSV file? ›

How to: Export Office 365 Users to CSV (online without using Powershell)
  1. Step 1: Login to your Office 365 admin account. Login to your Office 365 admin account online. ...
  2. Step 2: Click "Admin" at the top of the page. ...
  3. Step 3: Selecting the Export command. ...
  4. Step 4: Selecting Export Criteria.

How do I check when my Office 365 license expires in PowerShell? ›

You can check the license expiry date using any of the following methods. In the Admin Center, you need to navigate to Billing–> Products & Services. It will show Office 365 subscription plan, expiry date. If you are a hater of ever-changing admin portals, I'd suggest you use PowerShell.

How do I install MSOnline modules? ›

Open an elevated Windows PowerShell command prompt (run Windows PowerShell as an administrator). Run the Install-Module MSOnline command. If you're prompted to install the NuGet provider, type Y and press Enter. If you're prompted to install the module from PSGallery, type Y and press Enter.

How do I get my license report from Office 365? ›

Using the O365 admin portal, you can get user's license information, but you need to click each user to know about their license subscriptions and service status which is a cumbersome task. To ease your work, you can use PowerShell commands.

How do I remove an e3 license from Office 365? ›

In the Microsoft 365 admin center, select User management. Select the employee that you want to block, and then choose Licenses and Apps. On the Licenses and Apps page, un-check the box next to the subscription to remove the license and click Save changes.

What is usage location Office 365? ›

In Office 365 it is known as the UsageLocation attribute. It is an important attribute in Office 365 because it determines what Office 365 Licenses and and associated features can be assigned to a user based on geographic availability and laws.

Videos

1. Support Webcast, Getting Started with Project Pro for O365 and using it with Project Online
(Office)
2. Webinar: Azure B2B and Guest Management Best Practices
(Extranet User Manager and Envision IT)
3. Troubleshooting Office 365
(Robert Crane)
4. Training Videos Microsoft 365 SMB Enabling Microsoft 365 Business Voice with Direct Routing
(AudioCodes Media)
5. SC-300 Microsoft Identity and Access Administrator Study Cram
(John Savill's Technical Training)
6. Extranets in SharePoint and Office 365
(Extranet User Manager and Envision IT)

Top Articles

You might also like

Latest Posts

Article information

Author: Saturnina Altenwerth DVM

Last Updated: 11/24/2022

Views: 5489

Rating: 4.3 / 5 (64 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Saturnina Altenwerth DVM

Birthday: 1992-08-21

Address: Apt. 237 662 Haag Mills, East Verenaport, MO 57071-5493

Phone: +331850833384

Job: District Real-Estate Architect

Hobby: Skateboarding, Taxidermy, Air sports, Painting, Knife making, Letterboxing, Inline skating

Introduction: My name is Saturnina Altenwerth DVM, I am a witty, perfect, combative, beautiful, determined, fancy, determined person who loves writing and wants to share my knowledge and understanding with you.