Office 365 – User Licensing basics using PowerShell

I’ve been doing quite a bit of work around Office 365 lately, and have been getting a number of question’s around licensing of users.

In this post ill cover the most basic commands needed for managing users. Sometime i’ll hopefully find the time to write a post covering some of the more detailed options available when managing licenses.

Salamander Active Directory
Firstly, I should say that Salamander Active Directory can now handle the Licensing needs for most schools.

It can be used to manage the licenses for existing users as well as new starters and leavers.

Connecting to Office 365
The first step is to connect to Office 365. If your not familar with this, have a look at this post:

List all the License Plans
Licenses are packaged into plans. When you are working in Office 365 online, you’ll see the ‘display’ name for these, but when working in Powershell you need to know their ‘real’ name, or AccountSKU.

You can very quickly get a list of the AccountSKU’s in your Tenancy using:

#Basic command

#More detailed information
Get-MsolAccountSku | Format-Table AccountSkuId, SkuPartNumber, ActiveUnits, ConsumedUnits

Service Plans
Once you’ve established the names of the Plans, it is often useful to look at the service plans inside those. Often it may be that a user doesn’t need to have all the available service plans when configuring licenses.

In my Office 365 setup, i have a number of License plans, including:


In the Office 365 Admin Centre this shows as:


In Powershell, you can get a list of these service plans using:

$ServicePlans = Get-MsolAccountSku | Where {$_.AccountSkuId -eq "SalamanderSoft:ENTERPRISEPACK"}

This will list the available service plans in the Pack selected.

In my tenancy these are:


Seeing the licenses for a single user
Sometimes its useful to view the license status for an exsiting user. This is easily done using the following:

$user = ""
(Get-MSOLUser –UserPrincipalName $user).Licenses[0].ServiceStatus


Add a License for a single user
Adding a license with a full pack is very straight forward and can be done with a single command.

Here i am using the variable $user to define the user in question.
You could just add the Full UPN of the user instead.


$user = ""
Set-MsolUserLicense -UserPrincipalName $user -AddLicenses SalamanderSoft:ENTERPRISEPACK 

Adding a License using License Options
Where a user doesn’t need to get the full pack, you can add specific set of plans, by using Licence Options.

In this example, i have used the license options parameter to add the license, with some of the options disabled.

#Set License Options (to disable various plans)
$MyLicenseOptions = New-MsolLicenseOptions -AccountSkuId SalamanderSoft:ENTERPRISEPACK -DisabledPlans OFFICESUBSCRIPTION, RMS_S_ENTERPRISE,MCOSTANDARD

#Set Licenses using the options above
Set-MsolUserLicense -UserPrincipalName $user -AddLicenses SalamanderSoft:ENTERPRISEPACK -LicenseOptions $MyLicenseOptions

This will result in the Office 365 Admin page looking like this:


Removing a License for a single user
We can also remove the license for a single user with a single command.

Set-MsolUserLicense -UserPrincipalName $user -RemoveLicenses SalamanderSoft:ENTERPRISEPACK

Office 365 – Changing a Username

Recently, i’ve been doing quite a bit of work with clients who have needed to change their usernames in Office 365 for one reason or another and have having difficulty.

In some cases they have managed to update it through the portal, but more often than not, its not quite worked properly and they have needed to change the User Principal Name manually using Powershell.

The good news is that its really straightforward to do. Infact, it’ll probably take you longer to get connected to Office 365 than it will to change the User Principal Name for a user.

Changing a single users User Principal Name
Once your connected (see my blog post on connecting to Office 365) you can simply run the powershell:

#Changing the UserPrincipalName for a single user
Set-MsolUserPrincipalName -UserPrincipalName "" -NewUserPrincipalName ""

This will do simply that, load the object for the user and change their Upn.

If you wanted to do that with variables to make things a little tidier you can:

#Chaning the UserPrincipalName for a single user - using variables
$oldUPN = ""
$newUPN = ""
Set-MsolUserPrincipalName -UserPrincipalName $oldUPN -NewUserPrincipalName $newUPN

Changing more than one
This works really nicely, but last week I had a customer who wanted to change around 30 for various reasons, so I had them make a CSV file to hold the details in 2 columns:


Once they’d generated this file, I simply used the below to change the User Principal Name for everyone in the CSV.

#Using a CSV File to change the UPN's
$path = "c:\pathtomycsv\upnChanges.csv"
Import-csv -path $path | 
foreach-object `
  Set-MsolUserPrincipalName -UserPrincipalName $_.oldUPN -NewUserPrincipalName $_.newUPN


Finding old, inactive users and computers in on-premise Active Directory using Powershell

One of the questions I get asked frequently is “How can I work out how many of my users or computers are inactive or old?”

Well, there are a number of ways to do this, but I’ve found that the easiest and certainly the quickest has been to use PowerShell.

Now, ill say right at the outset, that all I’m doing here is showing you the quickest way I’ve found to get a list of inactive or disabled users, nothing more.

I know there is much, much more that we can do with it, and get really clever with the scripting. I know, I’ve done it, but for the most part, the people who ask me literally want a list of users, nothing more.

So that’s all I’m going to do.

What am I looking for?
Active Directory stores a whole lot more information than you expect inside the objects for users and computers.  A couple of these are useful in determining how long account has been dormant or inactive.

These might include ‘lastLogonTimeStamp’ or looking at the ‘userAccountControl’ to see what their status is. There’s a load more you can look at too, but you don’t need to. You can get the basic details you need from a single command-let.

So, How do I get this information out using PowerShell.

NOTE: The following assumes that you are in PowerShell, have added the Active Directory modules and have relevant AD Permissions.

There are a number of solutions for this, most of them are using the Get-ADUser or Get-ADObject cmdlets. There are many articles around on how to do this, but for the most part, it is much easier to use the cmdlet ‘Search-ADAccount’

Search-ADAccount can be used with a number of switches, but the most common ones are:


Today, we’ll briefly look at -AccountInactive and -AccountDisabled

Disabled Accounts
We all disable accounts regularly, but remembering which accounts can often be a memory challenge. We can address this simply by using the -AccountDisabled switch.

#Return all ADAccounts which are disabled
Search-ADAccount -AccountDisabled

This will quite simply list all the current AD accounts (users and computers which are disabled)

You can filter this to just Users or Computers using one of the 2 parameters below:


You may want to export this data to a csv file that you can use later. This can easily be done with using Export-CSV

#User Search-ADAccount to export a list of all the users which are disabled
Search-ADAccount -AccountDisabled -UsersOnly| Export-Csv "c:\export.csv"

Inactive Accounts
Very similarly to the disabled accounts, it is very straightforward to identify those accounts which are inactive using -AccountInactive

#Return all AD Accounts which are inactive
Search-ADAccount -AccountInactive

You can also filter them using the -UserOnly / -ComputerOnly parameters.

Filtering Inactive Accounts after a certain time
With the -AccountInactive switch you can also quickly find those users that have been inactive for a period of time, such as 90 days, using the -TimeSpan parameter.

Search-ADAccount -AccountInactive -TimeSpan 30

Again, you can export this to a csv or similar using the Export-csv as above.

What’s next
There’s a lot more you can do with this disabled or inactive accounts, and we’ve barely touched on this cmdlet itself.

This may not be the best way for you, but if you just need a really quick overview of your disabled or inactive accounts, then this is probably the quickest and easiest way to get it.

Connecting to Office 365 Using PowerShell

More and more the focus is on Office 365, and a lot of the niftier management can/should be done with PowerShell.

Recently, i have been working more and more with Office 365, and connecting to it can be a bit of a pain.

Here, I will demonstrate a couple of ways that you can connect to Office 365 easily, as something you will be doing more and more.

I will also demonstrate a way that you can save the password securely in a separate file, so you don’t have to keep entering it, or have it available in plain text.

Connecting to Office 365 – Prerequisites
Firstly, in order to connect to Office 365 you must have the Windows Azure AD Module for PowerShell installed.

You can find this here:

Connecting to Office 365
A quick Google will give you then commands you need to connect to Office 365 from your new Shell, but i tend to use this set of commands.

#Connect to Office 365, Prompting for Credentials
Import-Module MSOnline
$O365Cred = Get-Credential
$O365Session = New-PSSession –ConfigurationName Microsoft.Exchange -ConnectionUri -Credential $O365Cred -Authentication Basic -AllowRedirection
Import-PSSession $O365Session
Connect-MsolService –Credential $O365Cred

In its most basic form, this will Import the MSOnline powershell module (the one you have just installed) and connect to the Office 365 Service, prompting for your username and password.

This works well, but if you use it often, it can be a pain to keep giving your credentials.

Saving the Password Securely
You can simply add the password to the script, but this will be in plain text, which is not ideal.

To save the password in a more secure fashion, I use the PowerShell script below:

#Set location of TXT file to store the password
$secureFilePath = "D:\365SecureString.txt"

#Enter the password when prompted
#It will be stored in a secure string
Read-Host -Prompt "Enter password to be encrypted in secure string text file" -AsSecureString |
ConvertFrom-SecureString |
#Location of the file to secure the string inside
Out-File $secureFilePath

This will prompt you for a password and save it in a more secure fashion to the file you specify at the top.

Once this file is saved, it can be accessed by any other PowerShell script, simply by reading the file

$pass = GetContent $secureFilePath | ConvertTo-SecureString

Want more on Passwords?
Check out Todd Klindt’s post on using Passwords with PowerShell HERE

Disclaimer on Secure Passwords
Unfortunately, I have to say that there are a couple of ways that this password can be read later on, but only by someone who has the knowledge and access to your file. It will certainly stop someone stumbling upon it.

Putting it together
Now that i have my password stored, you can add this location to the script to connect, and with a couple of tweaks have as script that will connect to Office 365 without any prompting.

Here, I’ve added it as a function. This was, i could save this into my PowerShell Profile so i could access it easily every time I needed it.

Function Connect365 {
    #Location of Password in TXT file
    $secureFilePath = "D:\365SecureString.txt"
    $userName = ""
    $pass = Get-Content $secureFilePath | ConvertTo-SecureString                                                           
    $O365Cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $userName,$pass     

    #Function to connect to MSOL using the secure string
    Import-Module MSOnline

    #$O365Cred = Get-Credential
    $O365Session = New-PSSession –ConfigurationName Microsoft.Exchange -ConnectionUri -Credential $O365Cred -Authentication Basic -AllowRedirection
    Import-PSSession $O365Session
    Connect-MsolService –Credential $O365Cred


I’ll cover the use of functions a little more in another blog.

Working with Active Directory in Powershell – Finding and exporting user information

Most of us work primarily with Active Directory Users and Computers, and for the most part this works fine. Sometimes though, its easier to do the things we need to do with PowerShell.

In this post, ill cover the basics of using PowerShell with Active Directory to get user information.

Connecting to Active Directory
If you are working on a Server with an Active Directory Role (Domain Controller etc.) you will already have all the tools you need. You can either open the Active Directory Module for PowerShell from start.

Or you can open PowerShell and add the Active Directory Module

Import-Module Active Directory

If you are working on a machine which is not a Server with an AD role, you will need to be on a machine which is a member of the domain you want to query and has the ‘Remote Server Administration Tools’ or ‘RSAT’ installed.

For more information on installing RSAT, see this post on TechNet

Once you have RSAT installed, ensure you have the Active Directory Module for PowerShell installed.



Testing the Connection to Active Directory.
Once you have PowerShell open, you can check that you can communicate Active Directory easily using the command


This will simply connect to Active Directory and output some basic details above the domain.


The Get-ADUser Commandlet
The only cmdlet we’ll use here is ‘Get-ADUser’

As with every PowerShell CommandLet you can use the Get-Help to get detailed information on the parameters you can use.

Get-Help Get-ADUser

You can also use -Examples to get some sample code

Get-Help Get-ADUser -Examples

Finding Users
Firstly, we can use the Get-ADUser cmdlet to retrieve all the users in the Domain:

Get-ADUser -Filter *

This will retrieve every user in Active Directory and output this as list.

However, this isn’t very useful, as it most likely won’t contain the attributes you need.

By default, only a small set of attributes are retrieved. You can specify the attributes to be retrieved using:

-Properties *

This will add every property for a user, but you can then us the ‘select’ option to display only the attributes you want.

| select <attributeName>, <attributeName2>
Get-ADUser -Filter * -Properties * | select sAMAccountName, givenName, surname

You can select as many attributes as you want, but if you add more than 4, the way the information is displayed will change from a tabular format to a 1 line per attribute.


Exporting the retrieved information
your probably querying active directory in order to do something with the information, and for that you may want the data exported into a usable format. You can export to a csv file by adding

| Export-Csv "C:\pathtoexportto\filename.csv" -noType
Get-ADUser -Filter * | select sAMAccountName, givenName, surname

Filtering which OU’s to query
So far we have only queried the full domain. To choose where the base of the query should be, you can add the Property -SearchBase

-SearchBase "OU=nameofou,DC=domain,DC=local"
Get-ADUser -Filter * -SearchBase "OU=Staff,OU=Users,OU=Salamander-Sims,DC=salamandertest,DC=co,DC=uk" | select sAMAccountName

Find a specific user
If you want to select a user specifically you can specify the parameter -Identity followed by the account name

Get-ADUser -Identity myusername

Adding filters based on attributes

You can also filter users using their attributes with the Filter Parameter

Get-ADUser -Filter {givenName -eq "Ben"
Get-ADUser -Filter {(givenName -eq "John") -and (sn -eq "Smith")}

You can also use the -like parameter when filtering. Here we query any user where they have an email address.

Get-ADUser -Filter {mail -like "*"}