Automated Office 365 Licensing v1.0

Originally I created this script and posted about it here, but since then I’ve expanded it to a more friendly utility. The utility will add a specific Office 365 license to a batch of users within an OU structure. It can take some time to run depending on the amount of users. I’ve used it in environments with thousands of users and generally schedule it to run once a day.

This utility is available to download from the Microsoft TechNet Gallery and GitHub.

-Mike

Twitter – @Digressive

 

Features and Requirements

This utility will assign a configurable Office 365 license to Active Directory user accounts within an OU or descending OUs. All options are added via command line switches. Options include:

  • The Office 365 Global Admin user and password to use.
  • The Office 365 license and usage location to assign.
  • Organisation Unit which contains to users to license.
  • The directory to output a log file to.
  • An optional email address to send the log file to.

This utility has been tested running on Windows Server 2016. This utility requires the MSOnline and Active Directory PowerShell modules to be installed.

 

The -file Parameter

When running the script via Schedule Tasks or the command prompt be sure to use the -file parameter before specifying the script, so you can use “double quotes” for the command line switches that need them, if you do not use -file, then you should use ‘single quotes’.

 

Generating A Password File

The password used for SMTP server authentication must be in an encrypted text file. To generate the password file, run the following command in PowerShell, on the computer that is going to run the script and logged in with the user that will be running the script. When you run the command you will be prompted for a username and password. Enter the username and password you want to use to authenticate to your SMTP server.

Please note: This is only required if you need to authenticate to the SMTP server when send the log via e-mail.

$creds = Get-Credential
$creds.Password | ConvertFrom-SecureString | Set-Content c:\scripts\ps-script-pwd.txt

After running the commands, you will have a text file containing the encrypted password. When configuring the -Pwd switch enter the path and file name of this file.

 

Configuration

The table below shows all the command line options available with descriptions and example configurations.

Command Line Switch Mandatory Description Example
-User365 Yes The Office 365 Admin user to use for the operation.
GAdmin@contosocom.onmicrosoft.com
-Pwd365 Yes The password for the Office 365 Admin user to use for the operation.
P@ssw0rd
-Lic Yes The Office 365 license code to apply to your users.
contosocom:ENTERPRISEPACK
-UseLoc Yes The Office 365 usage location to use.
GB
-OU Yes The top level OU that contains the users to license in Office 365. “ou=My_O365_Users,dc=contoso,dc=com”
-L No Location to store the optional log file. The name of the log file is automatically generated. C:\foo
-SendTo No The email address to send the log file to. me@contoso.com
-From No* The email address that the log file should be sent from.

*This switch isn’t mandatory but is required if you wish to email the log file.

example@contoso.com
-Smtp No* SMTP server address to use for the email functionality.

*This switch isn’t mandatory but is required if you wish to email the log file.

mail01.contoso.com

OR

smtp.live.com

OR

smtp.office365.com

-User No* The username of the account to use for SMTP authentication.

*This switch isn’t mandatory but may be required depending on the configuration of the SMTP server.

example@contoso.com
-Pwd No* The location of the file containing the encrypted password of the account to use for SMTP authentication.

*This switch isn’t mandatory but may be required depending on your SMTP server.

c:\foo\ps-script-pwd.txt
-UseSsl No* Add this option if you wish to use SSL with the configured SMTP server.

Tip: If you wish to send email to outlook.com or office365.com you will need this.

*This switch isn’t mandatory but may be required depending on the configuration of the SMTP server.

N/A

 

Change Log

2018-04-11 1.0

  • Initial release.

 

PowerShell Code


<#PSScriptInfo .VERSION 1.0 .GUID d89e65ae-1bed-4991-a54f-dd70a4e34996 .AUTHOR Mike Galvin twitter.com/digressive .COMPANYNAME .COPYRIGHT (C) Mike Galvin. All rights reserved. .TAGS Microsoft Office 365 Licensing Automation .LICENSEURI .PROJECTURI https://gal.vin/2018/11/04/automated-office-365-licensing/ .ICONURI .EXTERNALMODULEDEPENDENCIES MSOnline and Active Directory PowerShell Modules .REQUIREDSCRIPTS .EXTERNALSCRIPTDEPENDENCIES .RELEASENOTES #>

<# .SYNOPSIS Assigns licenses to Office 365 users in an Active Directory OU structure. .DESCRIPTION Assigns licenses to Office 365 users in an Active Directory OU structure. This script will: Take users in a specified OU structure and will assign Office 365 licenses to users that aren't licensed. Important note #1: The MSOnline PowerShell management modules should be installed for this script to run successfully. Important note #2: Depending on the number of users in the OU structure this script can take a long time to run. .PARAMETER User365 The Office 365 Admin user to use for the operation. .PARAMETER Pwd365 The password for the Office 365 Admin user to use for the operation. .PARAMETER Lic The Office 365 license to apply to your users. .PARAMETER UseLoc The Office 365 usage location to use. .PARAMETER OU The top level OU that contains the users to license in Office 365. .PARAMETER L The path to output the log file to. The file name will be Office-365-Licensing.log .PARAMETER SendTo The e-mail address the log should be sent to. .PARAMETER From The from address the log should be sent from. .PARAMETER Smtp The DNS or IP address of the SMTP server. .PARAMETER User The user account to connect to the SMTP server. .PARAMETER Pwd The txt file containing the encrypted password for the user account. .PARAMETER UseSsl Connect to the SMTP server using SSL. .EXAMPLE Office-365-Licensing.ps1 -User365 GAdmin@contosocom.onmicrosoft.com -Pwd365 P@ssw0rd -Lic contosocom:ENTERPRISEPACK -UseLoc GB -OU OU=MyUsers,DC=contoso,DC=com -L C:\logs -SendTo me@contoso.com -From Office-365-licensing@contoso.com -Smtp smtp.outlook.com -User user -Pwd C:\foo\pwd.txt -UseSsl This will login to Office 365 with the specified user and assign licenses to the users in the MyUsers OU, and OUs below that. On completion it will email the log file to the specified address. #>

## Set Params via cmd
[CmdletBinding()]
Param(
    [parameter(Mandatory=$True)]
    [alias("User365")]
    $365AdUser,
    [parameter(Mandatory=$True)]
    [alias("Pwd365")]
    $365Password,
    [parameter(Mandatory=$True)]
    [alias("Lic")]
    $License,
    [parameter(Mandatory=$True)]
    [alias("UseLoc")]
    $UsageLocation,
    [parameter(Mandatory=$True)]
    [alias("OU")]
    $OUDN,
    [alias("L")]
    [ValidateScript({Test-Path $_ -PathType 'Container'})]
    $LogPath,
    [alias("SendTo")]
    $MailTo,
    [alias("From")]
    $MailFrom,
    [alias("Smtp")]
    $SmtpServer,
    [alias("User")]
    $SmtpUser,
    [alias("Pwd")]
    [ValidateScript({Test-Path -Path $_ -PathType Leaf})]
    $SmtpPwd,
    [switch]$UseSsl)

## Log in to Office 365
$365PwdSecure = ConvertTo-SecureString $365Password -AsPlainText -Force
$365Cred = New-Object System.Management.Automation.PSCredential $365AdUser, $365PwdSecure

## Connect to Azure AD
Connect-MsolService -Credential $365Cred

## Get Users from local AD to compare to Azure AD
$ADUsers = Get-ADUser -Filter * -SearchBase $OUDN

## Create a variable that contains the users who are not licensed
$LicNo = ForEach ($ADUser in $ADUsers)
{
    ## Get Azure AD users by UPN
    $UserLic = Get-MsolUser -UserPrincipalName $ADUser.UserPrincipalName
 
    ## If user has no license, output something so we can count it
    If ($UserLic.IsLicensed -eq $false)
    {
        Write-output "$($ADUser.UserPrincipalName) is unlicensed"
    }
}

## Count the users who are not licensed. If the variable does not equal zero, then license the users.
If ($LicNo.count -ne 0)
{
    ## If logging is configured, start log
    If ($LogPath)
    {
        $LogFile = "Office-365-Licensing.log"
        $Log = "$LogPath\$LogFile"

        ## If the log file already exists, clear it
        $LogT = Test-Path -Path $Log

        If ($LogT)
        {
            Clear-Content -Path $Log
        }

        Add-Content -Path $Log -Value "****************************************"
        Add-Content -Path $Log -Value "$(Get-Date -Format g) Log started"
        Add-Content -Path $Log -Value ""
    }

    ## For each user Azure AD user from the OU configured above.
    ForEach ($ADUser in $ADUsers)
    {
        ## Get Azure AD users UPN.
        $UserLic = Get-MsolUser -UserPrincipalName $ADUser.UserPrincipalName

        ## If user has no license set one.
        If ($UserLic.IsLicensed -eq $false)
        {
            Set-MsolUser -UserPrincipalName $ADUser.UserPrincipalName –UsageLocation $UsageLocation
            Set-MsolUserLicense -UserPrincipalName $ADUser.UserPrincipalName -AddLicenses $License
            
            ## If log is configured then log the user being licensed
            If ($LogPath)
            {
                Add-Content -Path $Log -Value "$(Get-Date -Format g) Office 365 License added for $($ADUser.UserPrincipalName)"
            }
        }
    }

    ## If log is configured, stop the log
    If ($LogPath)
    {
        Add-Content -Path $Log -Value ""
        Add-Content -Path $Log -Value "$(Get-Date -Format g) Log finished"
        Add-Content -Path $Log -Value "****************************************"

        ## If email was configured, set the variables for the email subject and body
        If ($SmtpServer)
        {
            $MailSubject = "Office 365 Licensing"
            $MailBody = Get-Content -Path $Log | Out-String

            ## If an email password was configured, create a variable with the username and password
            If ($SmtpPwd)
            {
                $SmtpPwdEncrypt = Get-Content $SmtpPwd | ConvertTo-SecureString
                $SmtpCreds = New-Object System.Management.Automation.PSCredential -ArgumentList ($SmtpUser, $SmtpPwdEncrypt)

                ## If ssl was configured, send the email with ssl
                If ($UseSsl)
                {
                    Send-MailMessage -To $MailTo -From $MailFrom -Subject $MailSubject -Body $MailBody -SmtpServer $SmtpServer -UseSsl -Credential $SmtpCreds
                }

                ## If ssl wasn't configured, send the email without ssl
                Else
                {
                    Send-MailMessage -To $MailTo -From $MailFrom -Subject $MailSubject -Body $MailBody -SmtpServer $SmtpServer -Credential $SmtpCreds
                }
            }
        
            ## If an email username and password were not configured, send the email without authentication
            Else
            {
                Send-MailMessage -To $MailTo -From $MailFrom -Subject $MailSubject -Body $MailBody -SmtpServer $SmtpServer
            }
        }
    }
}

## End


 

One Comment Add yours

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.