0% found this document useful (0 votes)
925 views143 pages

Manage Office 365 With Office 365 PowerShell

Office 365 PowerShell provides capabilities beyond the admin center for efficiently managing Office 365 at scale. Some key benefits of using Office 365 PowerShell include: - Revealing additional information not visible in the admin center - Configuring features only possible via PowerShell - Performing bulk operations more easily - Filtering large amounts of data - Printing/saving output - Managing across Exchange, SharePoint, Skype services Understanding basic PowerShell skills is important as some tasks require its use. While not replacing the admin center, PowerShell augments Office 365 management abilities.

Uploaded by

tracy_v
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
925 views143 pages

Manage Office 365 With Office 365 PowerShell

Office 365 PowerShell provides capabilities beyond the admin center for efficiently managing Office 365 at scale. Some key benefits of using Office 365 PowerShell include: - Revealing additional information not visible in the admin center - Configuring features only possible via PowerShell - Performing bulk operations more easily - Filtering large amounts of data - Printing/saving output - Managing across Exchange, SharePoint, Skype services Understanding basic PowerShell skills is important as some tasks require its use. While not replacing the admin center, PowerShell augments Office 365 management abilities.

Uploaded by

tracy_v
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 143

Table of Contents

Manage Office 365 with Office 365 PowerShell


Getting started with Office 365 PowerShell
Why you need to use Office 365 PowerShell
Connect to Office 365 PowerShell
Connect to all Office 365 services in a single Windows PowerShell window
Use Windows PowerShell to create reports in Office 365
Cmdlet references for Office 365 services
Office 365 PowerShell community resources
Manage user accounts and licenses with Office 365 PowerShell
View licenses and services with Office 365 PowerShell
View licensed and unlicensed users with Office 365 PowerShell
Assign licenses to user accounts with Office 365 PowerShell
View account license and service details with Office 365 PowerShell
Assign roles to user accounts with Office 365 PowerShell
Disable access to services with Office 365 PowerShell
Remove licenses from user accounts with Office 365 PowerShell
Block user accounts with Office 365 PowerShell
Delete and restore user accounts with Office 365 PowerShell
Create user accounts with Office 365 PowerShell
View user accounts with Office 365 PowerShell
Configure user account properties with Office 365 PowerShell
Manage SharePoint Online with Office 365 PowerShell
Create SharePoint Online sites and add users
Manage SharePoint Online users and groups
Manage SharePoint Online site groups
Manage Exchange Online with Office 365 PowerShell
Use PowerShell for email migration to Office 365
Use PowerShell to perform a cutover migration to Office 365
Use PowerShell to perform an IMAP migration to Office 365
Use PowerShell to perform a staged migration to Office 365
Manage Office 365 with Windows PowerShell for Delegated Access partners
Manage Office 365 tenants with Windows PowerShell for Delegated Access partners
Add a domain to a client tenancy with Windows PowerShell for Delegated Access
partners
Connect to Exchange Online via remote Windows PowerShell for Delegated Access
partners
Retrieve customer reporting data via Windows PowerShell for Delegated Access
partners
Aggregate customer reporting data via Windows PowerShell for Delegated Access
partners
Manage Skype for Business Online with Office 365 PowerShell
Manage Skype for Business Online policies with Office 365 PowerShell
Assign per-user Skype for Business Online policies with Office 365 PowerShell
Manage Office 365 with Office 365 PowerShell
4/16/2018 • 1 min to read • Edit Online

Summary: Learn how to use Office 365 PowerShell with Office 365 users and licenses, Skype for Business
Online, SharePoint Online, Exchange Online, and the Office 365 Security & Compliance Center.
Office 365 PowerShell is a powerful management tool that complements the Office 365 Admin center. For
example, you can use Office 365 PowerShell automation to more quickly manage multiple user accounts and
licenses and create reports. Learn how to use Office 365 PowerShell with Office 365 users and licenses, Skype
for Business Online, SharePoint Online, Exchange Online, and the Office 365 Security & Compliance Center.
Select the topic based on your needs:
Getting started with Office 365 PowerShell
Start here if you are not familiar with Office 365 PowerShell and want to install the Office 365 PowerShell
modules and connect to your Office 365 tenant.
Manage user accounts and licenses with Office 365 PowerShell
Start here if you have installed the Office 365 PowerShell modules and want to learn more about using
automation commands to manage user accounts and licenses.
Office 365 PowerShell for SharePoint Online
Start here if you have installed the Office 365 PowerShell modules and want to use automation
commands to perform management of SharePoint Online.
Exchange Online PowerShell
Start here if you want to use automation commands to manage Exchange Online.
Use PowerShell for email migration to Office 365
Start here if you have installed the Office 365 PowerShell modules and want to migrate your email from
existing systems.
Office 365 Security & Compliance Center PowerShell
Start here if you want to use automation commands to manage the Security & Compliance Center.
Manage Office 365 with Windows PowerShell for Delegated Access Permissions (DAP ) partners
Start here if you want to use Syndication and Cloud Solution Provider (CSP ) partners to manage your
Office 365 customer tenants.
Manage Skype for Business Online with Office 365 PowerShell
Start here if you have installed the Office 365 PowerShell modules and want to perform management of
Skype for Business Online.
Skype for Business Online cmdlets
Start here if you are very comfortable with Office 365 PowerShell and want to learn more about specific
commands to manage dial-in conferencing, Cloud PBX, and PSTN calling settings for your organization,
and use the reporting features to monitor and report on Skype for Business Online usage.
Getting started with Office 365 PowerShell
2/13/2018 • 1 min to read • Edit Online

Summary: Understand the importance of Office 365 PowerShell, get connected to your Office 365 tenant, and
get help.
With Office 365 PowerShell, you can manage Office 365 with commands and scripts to streamline your daily
work. Learn why Office 365 PowerShell skills are crucial to managing Office 365, how to connect to your Office
365 subscription, create reports, and get additional information and help from the Office 365 community.
Select the article based on your needs:
Why you need to use Office 365 PowerShell
Start here if you are brand new to Office 365 PowerShell and learn six reasons why you need to use
Office 365 PowerShell.
Connect to Office 365 PowerShell
Start here to connect to your Office 365 subscription using Office 365 PowerShell and perform
administrative tasks from the command line.
Connect to all Office 365 services in a single Windows PowerShell window
You can manage Office 365 in separate windows for Skype for Business Online, SharePoint Online,
Microsoft Exchange Online, and Office 365 accounts and licenses. Alternately, can manage these from a
single window. This topic tells you how.
Use Windows PowerShell to create reports in Office 365
Start here if you have installed the Office 365 PowerShell modules and want to learn more about using
automation commands to quickly create reports.
Cmdlet references for Office 365 services
Start here to find the topics that describe the cmdlets for the Office 365 PowerShell modules.
Office 365 PowerShell community resources
Start here to connect to the PowerShell community venues and get help or ongoing information about
using Office 365 PowerShell .

See also
Manage Office 365 with Office 365 PowerShell
Why you need to use Office 365 PowerShell
4/19/2018 • 18 min to read • Edit Online

Summary: Understand why you must use Office 365 PowerShell to manage Office 365, in some cases more
efficiently and in other cases by necessity.
With the Office 365 admin center, you can not only manage your Office 365 user accounts and licenses, but you
can also manage your Office 365 server products: Exchange, Skype for Business Online, and SharePoint Online.
However, you can also manage these elements with Office 365 PowerShell commands, taking advantage of a
command-line and scripting language environment for speed, automation, and additional capability.
In this article, we'll show you these ways in which you can use Office 365 PowerShell to manage Office 365.
Office 365 PowerShell can reveal additional information that you cannot see with the Office 365 admin
center
Office 365 has features that you can only configure by using Office 365 PowerShell
Office 365 PowerShell is great at performing bulk operations
Office 365 PowerShell is great at filtering data
Office 365 PowerShell makes it easy to print or save data
Office 365 PowerShell lets you manage across server products
Before you begin, understand that Office 365 PowerShell is a set of modules for Windows PowerShell, a
command-line environment for Windows-based services and platforms. This environment creates a command
shell language that can be extended with additional modules and provides a way to execute simple or complex
commands or scripts. For example, after you install the Office 365 PowerShell modules and connect to your Office
365 subscription, you can run this command to list all of the user mailboxes for Microsoft Exchange Online:

Get-Mailbox

You can also run this command to calculate the number of items in all of the lists for all of the sites for all of your
web apps in SharePoint Online:

Get-SPOSite -Limit All | Get-SPWeb -Limit All | % {$_.Lists} | ? {$_ -is


[Microsoft.SharePoint.SPDocumentLibrary]} | % {$total+= $_.ItemCount}; $total

Getting the list of mailboxes can also be easily done using the Office 365 admin center, but counting the number of
items in all of the lists for all of the sites for all of your web apps cannot be easily done.
Please note that Office 365 PowerShell is designed to augment and enhance your ability to manage Office 365,
not to replace the Office 365 admin center. As an Office 365 administrator, you must become at least comfortable
with using Office 365 PowerShell because there are some configuration procedures that can only be done with
Office 365 PowerShell commands. In these cases, you will be required to understand how to:
Install the Office 365 PowerShell modules (done only once for each administrator computer).
Connect to your Office 365 subscription (done once for each PowerShell session).
Gather the information needed to run the required Office 365 PowerShell commands.
Run the Office 365 PowerShell commands successfully.
After learning these basic skills, you are not required to list your mailbox users with Get-Mailbox command, nor
are you required to understand how to create a new command like the previous one to count all the items in all the
lists for all of the sites for all of your web apps. Microsoft and the community of Office 365 administrators can help
you with that as needed.

Office 365 PowerShell can reveal additional information that you


cannot see with the Office 365 admin center
The Office 365 admin center displays a lot of useful information, but that doesn't mean that it displays all the
possible information that Office 365 stores on users, licenses, mailboxes, and sites. Here is an example for users
and groups in the Office 365 admin center:

For many purposes, this displays the information you need to know. However, there are times when you need
more. For example, Office 365 licensing (as well as the Office 365 features available to a user) depend in part on
that user's geographic location. The policies and features you can extend to a user who lives in the United States
might not be the same as the policies and features you can extend to a user who lives in India or in Belgium. You
can use the Office 365 admin center to determine a user's geographic location with these steps:
1. Double-click the user's Display Name.
2. In the user properties display pane, click details.
3. In the details display, click additional details.
4. Scroll down until you see the heading Country or region:

5. Write the user's display name and location on a piece of paper, or copy and paste it into Notepad.
You must repeat this procedure for each user. For many users, this can be a tedious task. With Office 365
PowerShell, you can display this information for all of your users with the following command:
Get-MsolUser | Select DisplayName, UsageLocation

NOTE
This command requires you to install the Windows Azure Active Directory module.

Here is an example of the display:

DisplayName UsageLocation
----------- -------------
Zrinka Makovac US
Bonnie Kearney GB
Fabrice Canel BR
Brian Johnson (TAILSPIN) US
Anne Wallace US
Alex Darrow US
David Longmuir BR

TIP
The interpretation of this Office 365 PowerShell command is: Get all of the users in the current Office 365 subscription ( Get-
MsolUser ), but only display the name and location for each user ( Select DisplayName, UsageLocation ).

Because Office 365 PowerShell supports a command shell language, you can further manipulate the information
obtained from the Get-MSolUser command. For example, maybe you'd like to sort these users by their location,
grouping all the Brazilian users together, all the United States users together, etc. Here is the command:

Get-MsolUser | Select DisplayName, UsageLocation | Sort UsageLocation, DisplayName

Here is an example of the display:

DisplayName UsageLocation
----------- -------------
David Longmuir BR
Fabrice Canel BR
Bonnie Kearney GB
Alex Darrow US
Anne Wallace US
Brian Johnson (TAILSPIN) US
Zrinka Makovac US

TIP
The interpretation of this Office 365 PowerShell command is: Get all of the users in the current Office 365 subscription, but
only display the name and location for each user and sort them first by their location, and then their names ( Sort
UsageLocation, DisplayName ).

You can also employ additional filtering. For example, if you only want to see information about users based in
Brazil, use this command:

Get-MsolUser | Where {$_.UsageLocation -eq "BR"} | Select DisplayName, UsageLocation


Here is an example of the display:

DisplayName UsageLocation
----------- -------------
David Longmuir BR
Fabrice Canel BR

TIP
The interpretation of this Office 365 PowerShell command is: Get all of the users in the current Office 365 subscription whose
location is Brazil ( Where {$_.UsageLocation -eq "BR"} ), then display the name and location for each user.

A Quick Note Regarding Larger Domains


If you have a very large domain with tens of thousands of users, trying some of the examples we show in this
article could lead to "throttling." That means that, based on things like computing power and available network
bandwidth, you're trying to do a little too much at one time. Because of that, larger organizations might want to
split some of these Office 365 PowerShell commands into two commands. For example, this one command
returns all the user accounts and shows the name and location for each:

Get-MsolUser | Select DisplayName, UsageLocation

That works great for smaller domains. In a large organization, however, you might need to split that into two
commands: one command to store the user account information in a variable and another command to display the
needed information. Here is an example:

$x = Get-MsolUser
$x | Select DisplayName, UsageLocation

The interpretation of this set of Office 365 PowerShell commands is:


Get all of the users in the current Office 365 subscription and store the information in a variable named $x ( $x
= Get-MsolUser ).
Display the contents of the variable $x, but only include the name and location for each user ( $x | Select
DisplayName, UsageLocation ).

Office 365 has features that you can only configure with Office 365
PowerShell
The Office 365 admin center is intended to provide access to the most common or meaningful administrative tasks
that apply to most people. In other words, the Office 365 admin center was designed so that the typical
administrator could use the tool to carry out the most common management tasks. By this definition, that means
that there are some tasks that can't be completed by using the Office 365 admin center.
For example, the Skype for Business Online Admin center provides a few options for creating custom meeting
invitations:
With these settings, you can add a touch of personalization and professionalism to meeting invitations. However,
there's more to meeting configuration settings than simply creating custom meeting invitations. For example, by
default, meetings allow:
Anonymous users to gain automatic entrance to each meeting.
Attendees to record the meeting.
All users from your organization to be designated as presenters when they join the meeting.
These settings are not available from the Skype for Business Online Admin center. However, you can control them
from Office 365 PowerShell. Here is a command that disables these three settings:

Set-CsMeetingConfiguration -AdmitAnonymousUsersByDefault $False -AllowConferenceRecording $False -


DesignateAsPresenter "None"

NOTE
This command requires that you install the Skype for Business Online PowerShell Module .

TIP
The interpretation of this Office 365 PowerShell command is: For the settings for new Skype for Business Online meetings (
Set-CsMeetingConfiguration ), disable allowing anonymous users to gain automatic entrance to meetings ( -
AdmitAnonymousUsersByDefault $False ), disable the ability for attendees to record meetings ( -
AllowConferenceRecording $False ), and do not designate all users from your organization as presenters ( -
DesignateAsPresenter "None" ).

If you change your mind and want to restore these default settings (all of them enabled), run this command:

Set-CsMeetingConfiguration -AdmitAnonymousUsersByDefault $True -AllowConferenceRecording $True -


DesignateAsPresenter "Company"

This is just one example. There are others, which is why you, as an Office 365 administrator, need to be
comfortable with running Office 365 PowerShell commands.
Office 365 PowerShell is great at carrying out bulk operations
Historically, visual interfaces like the Office 365 admin center are most valuable when you have a single operation
to perform. For example, if you need to disable one user account, you can use the Office 365 admin center to
quickly locate and clear a checkbox. This can be simpler than performing a similar operation in Office 365
PowerShell.
But if you have to change many things or some selected things within a large set of other things, the Office 365
admin center might not be the best use of your time. For example, if you had to change the prefix on thousands of
phone numbers or you needed to remove a specific user, Ken Myer, from all of your SharePoint Online sites, how
would you do that in the Office 365 admin center?
For the latter example, you have several hundred SharePoint Online sites and you don't know even know which
ones of which Ken Meyer is a member. That means you'll have to start at the Office 365 admin center and then
perform this procedure for each site:
1. Click the URL of the site.
2. In the site collection properties box, click the Web Site Address link to open the site.
3. On the site, click Share.
4. In the Share dialog box click the link that shows you all the users who have permissions to the site:

5. In the Shared With dialog box, click Advanced.


6. Scroll down the list of users, find and select Ken Myer (assuming he has permissions to the site), and then
click Remove User Permissions.
This can take a long time for several hundred sites.
The alternative is to use Office 365 PowerShell and the following command to remove Ken Myer from all of your
sites:

Get-SPOSite | ForEach {Remove-SPOUser -Site $_.Url -LoginName "[email protected]"}


NOTE
This command requires that you install the Connect to SharePoint Online PowerShell.

TIP
The interpretation of this Office 365 PowerShell command is: Get all of the SharePoint sites in the current Office 365
subscription ( Get-SPOSite ) and for each site, remove Ken Meyer from the list of users who can access it ( ForEach
{Remove-SPOUser -Site $_.Url -LoginName "[email protected]"} ).

Because we are telling Office 365 to remove Ken Meyer from every site, including those in which he does not have
access, the display of this command will show errors for those sites in which he does not currently have access. We
can use an additional condition on this command to remove Key Meyer only from the sites that have him in their
login list, but the listed errors cause no harm to the sites themselves. This command might take a few minutes to
run against hundreds of sites, rather than hours of working through the Office 365 admin center.
Here is another bulk operation example. Use this command to add Bonnie Kearney, a new SharePoint
administrator, to all of the sites in the organization:

Get-SPOSite | ForEach {Add-SPOUser -Site $_.Url -LoginName "[email protected]" -Group "Members"}

TIP
The interpretation of this Office 365 PowerShell command is: Get all of the SharePoint sites in the current Office 365
subscription and for each site, allow Bonnie Kearney access by adding her login name to the Members group of the site (
ForEach {Add-SPOUser -Site $_.Url -LoginName "[email protected]" -Group "Members"} ).

Office 365 PowerShell is great at filtering data


The Office 365 admin center provides several different ways to filter your data to quickly and easily locate a
targeted subset of information. For example, Exchange makes it easy to filter on practically any property of a user
mailbox. For example, here is the list of mailboxes for all the users who live in the city of Bloomington:
The Exchange Admin center also lets you combine filter criteria. For example, you can find the mailboxes for all the
people who live in Bloomington and who work in the Finance department.
However, there are limitations to what you can do in the Exchange Admin center. For example, maybe you'd like to
find the mailboxes of people who live in Bloomington or San Diego, or the mailboxes for all the people who don't
live in Bloomington.
With Office 365 PowerShell, you can get a list of mailboxes for all the people who live in the cities of Bloomington
or San Diego with this command:

Get-User | Where {$_.RecipientTypeDetails -eq "UserMailbox" -and ($_.City -eq "San Diego" -or $_.City -eq
"Bloomington")} | Select DisplayName, City

Here is an example of the display:

DisplayName City
----------- ----
Alex Darrow San Diego
Bonnie Kearney San Diego
Julian Isla Bloomington
Rob Young Bloomington
Zrinka Makovac San Diego

TIP
The interpretation of this Office 365 PowerShell command is: Get all of the users in the current Office 365 subscription who
have a mailbox in the cities of either San Diego or Bloomington ( Where {$_.RecipientTypeDetails -eq "UserMailbox" -
and ($_.City -eq "San Diego" -or $_.City -eq "Bloomington")} ), then display the name and city for each ( Select
DisplayName, City ).

To list all the mailboxes for people who live anywhere except Bloomington, here is the command:
Get-User | Where {$_.RecipientTypeDetails -eq "UserMailbox" -and $_.City -ne "Bloomington"} | Select
DisplayName, City

Here is an example of the display:

DisplayName City
----------- ----
MOD Administrator Redmond
Alex Darrow San Diego
Allie Bellew Bellevue
Anne Wallace Louisville
Aziz Hassouneh Cairo
Belinda Newman Charlotte
Bonnie Kearney San Diego
David Longmuir Waukesha
Denis Dehenne Birmingham
Garret Vargas Seattle
Garth Fort Tulsa
Janet Schorr Bellevue

TIP
The interpretation of this Office 365 PowerShell command is: Get all of the users in the current Office 365 subscription who
have a mailbox not located in the city of Bloomington ( Where {$_.RecipientTypeDetails -eq "UserMailbox" -and $_.City
-ne "Bloomington"} ), then display the name and city for each.

You can also use wildcard characters in your Office 365 PowerShell filters to match part of a name. For example,
suppose you're looking for a user account, and all you can remember is that their last name was Anderson, or
maybe Henderson, or maybe it was Jorgenson.
You could track down that user in the Office 365 admin center by using the search tool and carrying out three
different searches:
One for Anderson
One for Henderson
One for Jorgenson
Because all three of these names end in "son", you can tell Office 365 PowerShell to display all the users whose
name ends in "son". Here is the command:

Get-User -Filter '{LastName -like "*son"}'

TIP
The interpretation of this Office 365 PowerShell command is: Get all of the users in the current Office 365 subscription, but
use a filter that only lists the users whose last names end in "son" ( -Filter '{LastName -like "*son"}' ). The * stands for any
set of characters, which are letters in the case of the user's last name.

Office 365 PowerShell makes it easy to print or save data


The Office 365 admin center allows you to view lists of data. Here is an example of the Skype for Business Online
Admin center displaying a list of users who have been enabled for Skype for Business Online:
To save that information to a file, you must copy and paste it into a document or Excel. In either case, the copy
might require additional formatting. Additionally, the Office 365 admin center does not provide a way to directly
print the displayed list.
Fortunately, you can use Office 365 PowerShell to not only display the list, but save it to a file that can be easily
imported into Excel. Here is an example command to save Skype for Business Online user data to a comma-
separated values (CSV ) file, a file that can be easily imported as a table in an Excel worksheet:

Get-CsOnlineUser | Select DisplayName, UserPrincipalName, UsageLocation | Export-Csv -Path


"C:\Logs\SfBUsers.csv" -NoTypeInformation

Here is an example of the display:


TIP
The interpretation of this Office 365 PowerShell command is: Get all of the Skype for Business Online users in the current
Office 365 subscription ( Get-CsOnlineUser ), obtain only the user name, UPN, and location ( Select DisplayName,
UserPrincipalName, UsageLocation ), and then save that information in CSV file named C:\Logs\SfBUsers.csv ( Export-Csv
-Path "C:\Logs\SfBUsers.csv" -NoTypeInformation ).

You can also use options to save this list as an XML file or as an HTML page. In fact, with additional PowerShell
commands, you could save it directly as an Excel file, with any custom formatting you desire.
You can also send the output of an Office 365 PowerShell command that displays a list directly to the default
printer in Windows. Here is an example command:

Get-CsOnlineUser | Select DisplayName, UserPrincipalName, UsageLocation | Out-Printer

Here's what your printed document will look like:

TIP
The interpretation of this Office 365 PowerShell command is: Get all of the Skype for Business Online users in the current
Office 365 subscription, obtain only the user name, UPN, and location, and then send that information to the default
Windows printer ( Out-Printer ).

The printed document has the same simple formatting as the display within the Office 365 PowerShell command
window, but once you have created an Office 365 PowerShell command to list what you need, you just add | Out-
Printer to the end of the command to get a hard copy to work from.

Office 365 PowerShell lets you manage across server products


The different components that make up Office 365 are designed to work together. For example, suppose you add a
new user to Office 365 and, when you do, you specify such information as the user's department and phone
number. That information will then be available if you access the user's information using any of the Office 365
server products: Skype for Business Online, Exchange, or SharePoint Online.
But that's for common information that spans the suite of products. Product-specific information-for example,
information about a user's Exchange mailbox-is typically not available across the suite. For example, if you want to
know if a user's mailbox is enabled or not, that information is available only in the Exchange Admin center.
Suppose you'd like to make a report that shows the following information for all your users:
The user's display name
Whether the user is licensed for Office 365
Whether the user's Exchange mailbox has been enabled
Whether the user is enabled for Skype for Business Online
You currently cannot use the Office 365 admin center to easily produce such a report. Instead, you'll have to create
a separate document to store the information, like an Excel worksheet, and get all the user names and licensing
information from the Office 365 admin center, get mailbox information from the Exchange Admin center, get
Skype for Business Online information from the Skype for Business Online Admin center, and then collate and
combine that information.
The alternative is to use an Office 365 PowerShell script to compile that report for you.
The following example script is more complicated than the commands you have seen so far in this article. But, it
shows the potential of using Office 365 PowerShell to create views of information that are very difficult to do
otherwise. Here is the script that can compile and display the needed list:

$x = Get-MsolUser

foreach ($i in $x)


{
$y = Get-Mailbox -Identity $i.UserPrincipalName
$i | Add-Member -MemberType NoteProperty -Name IsMailboxEnabled -Value $y.IsMailboxEnabled

$y = Get-CsOnlineUser -Identity $i.UserPrincipalName


$i | Add-Member -MemberType NoteProperty -Name EnabledForSfB -Value $y.Enabled
}

$x | Select DisplayName, IsLicensed, IsMailboxEnabled, EnabledforSfB

Here is an example of the display:

DisplayName IsLicensed IsMailboxEnabled EnabledForSfB


----------- ---------- ---------------- --------------
Zrinka Makovac True True True
Bonnie Kearney True True True
Fabrice Canel True True True
Brian Johnson False True False
Anne Wallace True True True
Alex Darrow True True True
David Longmuir True True True
Katy Jordan False True False
Molly Dempsey False True False

The interpretation of this Office 365 PowerShell script is:


Get all of the users in the current Office 365 subscription and store the information in a variable named $x ( $x
= Get-MsolUser ).
Start a loop that runs over all the users in the variable named $x ( foreach ($i in $x) ).
Define a variable named $y and store the user's mailbox information in it ( $y = Get-Mailbox -Identity
$i.UserPrincipalName ).
Add a new property to the user information named IsMailBoxEnabled and set it to the value of the
IsMailBoxEnabled property of the user's mailbox ( $i | Add-Member -MemberType NoteProperty -Name
IsMailboxEnabled -Value $y.IsMailboxEnabled ).
Define a variable named $y and store the user's Skype for Business Online information in it ( $y = Get-
CsOnlineUser -Identity $i.UserPrincipalName ).
Add a new property to the user information named EnabledForSfB and set it to the value of the Enabled
property of the user's Skype for Business Online information ( $i | Add-Member -MemberType
NoteProperty -Name EnabledForSfB -Value $y.Enabled ).
Display the list of users, but include only their name, whether they are licensed, and the two new properties that
indicate whether their mailbox is enabled and whether they are enabled for Skype for Business Online ( $x |
Select DisplayName, IsLicensed, IsMailboxEnabled, EnabledforSfB ).

See also
Getting started with Office 365 PowerShell
Manage user accounts and licenses with Office 365 PowerShell
Use Windows PowerShell to create reports in Office 365
Connect to Office 365 PowerShell
5/22/2018 • 5 min to read • Edit Online

Summary: Connect to your Office 365 organization using Office 365 PowerShell to perform administration
tasks from the command line.
Office 365 PowerShell lets you to manage your Office 365 settings from the command line. Connecting to
Office 365 PowerShell is a simple three-step process where you install the required software, run the required
software, and then connect to your Office 365 organization.

TIP
New to PowerShell? See a video Overview of PowerShell, brought to you by LinkedIn Learning.

What do you need to know before you begin?


Estimated time to complete: 5 minutes
You can use the following versions of Windows:
Windows 10, Windows 8.1, Windows 8 or Windows 7 Service Pack 1 (SP1)
Windows Server 2016, Windows Server 2012 R2, Windows Server 2012, or Windows Server
2008 R2 SP1

NOTE
Use a 64-bit version of Windows. Support for the 32-bit version the Microsoft Azure Active Directory
Module for Windows PowerShell was discontinued in October of 2014.

These procedures are intended for users who are members of an Office 365 admin role. For more
information, see About Office 365 admin roles.

Connect with the Microsoft Azure Active Directory Module for


Windows PowerShell
Commands in the Microsoft Azure Active Directory Module for Windows PowerShell have Msol in their cmdlet
name.
Step 1: Install required software
These steps are required once on your computer, not every time you connect. However, you'll likely need to
install newer versions of the software periodically.
1. Install the 64-bit version of the Microsoft Online Services Sign-in Assistant: Microsoft Online Services
Sign-in Assistant for IT Professionals RTW.
2. Install the Microsoft Azure Active Directory Module for Windows PowerShell with these steps:
Open an administrator-level PowerShell command prompt.
Run the Install-Module MSOnline command.
If prompted to install the NuGet provider, type Y and press ENTER.
If prompted to install the module from PSGallery, type Y and press ENTER.
After installation, close the PowerShell command window.
Step 2: Connect to Azure AD for your Office 365 subscription
To connect with just an account name and password:
1. Run a Windows PowerShell command prompt.
2. In the Windows PowerShell command window, run the following commands:

$UserCredential = Get-Credential
Connect-MsolService -Credential $UserCredential

3. In the Windows PowerShell Credential Request dialog box, type your Office 365 work or school
account user name and password, and then click OK.
To connect with multi-factor authentication (MFA ):
1. Run a Windows PowerShell command prompt.
2. In the Microsoft Azure Active Directory Module for Windows PowerShell command window, run
the following command.

Connect-MsolService

3. In the Azure Active Directory PowerShell dialog box, type your Office 365 work or school account
user name and password, and then click Sign in.
4. Follow the instructions in the Azure Active Directory PowerShell dialog box to provide additional
authentication information, such as a verification code, and then click Sign in.
How do you know this worked?
If you don't receive any errors, you connected successfully. A quick test is to run an Office 365 cmdlet—for
example, Get-MsolUser —and see the results.
If you receive errors, check the following requirements:
A common problem is an incorrect password. Run Step 3 again. and pay close attention to the user
name and password you enter.
The Microsoft Azure Active Directory Module for Windows PowerShell requires that the
Microsoft .NET Framework 3.5.x feature is enabled on your computer. It's likely that your computer
has a newer version installed (for example, 4 or 4.5.x), but backwards compatibility with older versions of
the .NET Framework can be enabled or disabled. For more information, see the following topics:
For Windows Server 2012 or Windows Server 2012 R2, see Enable .NET Framework 3.5 by using
the Add Roles and Features Wizard
For Windows 8 or Windows 8.1, see Installing the .NET Framework 3.5 on Windows 8 or 8.1
For Windows 7 or Windows Server 2008 R2, see You can't open the Azure Active Directory
Module for Windows PowerShell
Your version of the Microsoft Azure Active Directory Module for Windows PowerShell might be
out of date. To check, run the following command in Office 365 PowerShell or the Microsoft Azure
Active Directory Module for Windows PowerShell:
(Get-Item
C:\Windows\System32\WindowsPowerShell\v1.0\Modules\MSOnline\Microsoft.Online.Administration.Automation
.PSModule.dll).VersionInfo.FileVersion

If the version number returned is lower than the value 1.0.8070.2, uninstall the Microsoft Azure Active
Directory Module for Windows PowerShell and install the latest version from the link in Step 1.
If you receive a connection error, see this topic: "Connect-MsolService: Exception of type was
thrown" error.

Connect with the Azure Active Directory PowerShell for Graph


module
Commands in the Azure Active Directory PowerShell for Graph module module have AzureAD in their cmdlet
name.
For procedures that require the new cmdlets in the Azure Active Directory PowerShell for Graph module, use
these steps to install the module and connect to your Office 365 subscription.

NOTE
See Azure Active Directory PowerShell for Graph module for information about the support for different versions of
Microsoft Windows.

Step 1: Install required software


These steps are required once on your computer, not every time you connect. However, you'll likely need to
install newer versions of the software periodically.
1. Open an elevated Windows PowerShell command prompt (run Windows PowerShell as an
administrator).
2. In the Administrator: Windows PowerShell command window, run this command:

Install-Module -Name AzureAD

If prompted about installing a module from an untrusted repository, type Y and press ENTER.
Step 2: Connect to Azure AD for your Office 365 subscription
To connect to your Office 365 subscription with an account name and password:

$UserCredential = Get-Credential
Connect-AzureAD -Credential $UserCredential

In the Windows PowerShell Credential Request dialog box, type your Office 365 work or school account
user name and password, and then click OK.
To connect to your Office 365 subscription with multi-factor authentication (MFA ):

Connect-AzureAD

In the Azure Active Directory PowerShell dialog box, type your Office 365 work or school account user name
and password, and then click Sign in.
Follow the instructions in the Azure Active Directory PowerShell dialog box to provide additional
authentication information, such as a verification code, and then click Sign in.
After connecting, you can use the new cmdlets for the Azure Active Directory PowerShell for Graph module.

See also
Manage Office 365 with Office 365 PowerShell
Getting started with Office 365 PowerShell
Connect to all Office 365 services in a single Windows PowerShell window
Get-Credential
Connect-MsolService
Connect to all Office 365 services in a single
Windows PowerShell window
4/23/2018 • 4 min to read • Edit Online

Summary: Instead of managing different Office 365 services in separate PowerShell console windows, you can
connect to all Office 365 services and manage them from single console window.
When you use PowerShell to manage Office 365, it is possible to have up to five different Windows PowerShell
sessions open at the same time corresponding to Office 365 admin center, SharePoint Online, Exchange Online,
Skype for Business Online, and the Security & Compliance Center. With five different connection methods in
separate Windows PowerShell sessions, your desktop could look like this:

This is not optimal for managing Office 365 because you can't exchange data among those five windows for cross-
service management. This topic describes how to use a single instance of Windows PowerShell from which you
can manage Office 365, Skype for Business Online, Exchange Online, SharePoint Online, and the Security &
Compliance Center.

Before you begin


Before you can manage all of Office 365 from a single instance of Windows PowerShell, consider the following
prerequisites:
The Office 365 work or school account that you use for these procedures needs to be a member of an
Office 365 admin role. For more information, see About Office 365 admin roles. This a requirement for
Office 365 PowerShell, not necessarily for all other Office 365 services.
You can use the following 64-bit versions of Windows:
Windows 10
Windows 8.1 or Windows 8
Windows Server 2016
Windows Server 2012 R2 or Windows Server 2012
Windows 7 Service Pack 1 (SP1)*
Windows Server 2008 R2 SP1*
You need to install the Microsoft .NET Framework 4.5.x and then either the Windows
Management Framework 3.0 or the Windows Management Framework 4.0. For more
information, see Installing the .NET Framework and Windows Management Framework 3.0 or
Windows Management Framework 4.0.
You need to use a 64-bit version of Windows because of the requirements for the Skype for Business
Online module and one of the Office 365 modules.
You need to install the modules that are required for Azure AD, SharePoint Online, and Skype for Business
Online:
Azure Active Directory V2
SharePoint Online Management Shell
Skype for Business Online, Windows PowerShell Module
Windows PowerShell needs to be configured to run signed scripts for Skype for Business Online, Exchange
Online, and the Security & Compliance Center. To do this, run the following command in an elevated
Windows PowerShell session (a Windows PowerShell window you open by selecting Run as
administrator).

Set-ExecutionPolicy RemoteSigned

Connection steps when using a password


Here are the steps to connect to all the services in a single PowerShell window.
1. Open Windows PowerShell as an administrator (use Run as administrator).
2. Run this command, and enter your Office 365 work or school account credentials.

$credential = Get-Credential

3. Run this command to connect to Azure Active Directory (AD ).

Connect-AzureAD -Credential $credential

4. Run these commands to connect to SharePoint Online. Replace <domainhost> with the actual value for
your domain. For example, for litwareinc.onmicrosoft.com , the <domainhost> value is litwareinc .

Import-Module Microsoft.Online.SharePoint.PowerShell -DisableNameChecking


Connect-SPOService -Url https://<domainhost>-admin.sharepoint.com -credential $credential

5. Run these commands to connect to Skype for Business Online. A warning about increasing the
WSMan NetworkDelayms value is expected the first time you connect and should be ignored.

Import-Module SkypeOnlineConnector
$sfboSession = New-CsOnlineSession -Credential $credential
Import-PSSession $sfboSession
6. Run these commands to connect to Exchange Online.

$exchangeSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri


"https://outlook.office365.com/powershell-liveid/" -Credential $credential -Authentication "Basic" -
AllowRedirection
Import-PSSession $exchangeSession

7. Run these commands to connect to the Security & Compliance Center.

$SccSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri


https://ps.compliance.protection.outlook.com/powershell-liveid/ -Credential $credential -Authentication
"Basic" -AllowRedirection
Import-PSSession $SccSession -Prefix cc

Here are all the commands in a single block. Specify the name of your domain host, and then run them all at one
time.

$domainHost="<domain host name, such as litware for litwareinc.onmicrosoft.com>"


$credential = Get-Credential
Connect-AzureAD -Credential $credential
Import-Module Microsoft.Online.SharePoint.PowerShell -DisableNameChecking
Connect-SPOService -Url https://$domainHost-admin.sharepoint.com -credential $credential
Import-Module SkypeOnlineConnector
$sfboSession = New-CsOnlineSession -Credential $credential
Import-PSSession $sfboSession
$exchangeSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri
"https://outlook.office365.com/powershell-liveid/" -Credential $credential -Authentication "Basic" -
AllowRedirection
Import-PSSession $exchangeSession
$SccSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri
https://ps.compliance.protection.outlook.com/powershell-liveid/ -Credential $credential -Authentication
"Basic" -AllowRedirection
Import-PSSession $SccSession -Prefix cc

When you are ready to close down the Windows PowerShell window, run this command to remove the active
sessions to Skype for Business Online, Exchange Online, SharePoint Online, and the Security & Compliance
Center:

Remove-PSSession $sfboSession ; Remove-PSSession $exchangeSession ; Remove-PSSession $SccSession ; Disconnect-


SPOService

Connection steps when using multi-factor authentication


Here are all the commands in a single block to connect to Azure AD, SharePoint Online, and Skype for Buiness
using multi-factor authentication in a single window. Specify the user principal name (UPN ) name of a global
administrator account and your domain host name, and then run them all at one time.

$acctName="<UPN of a global administrator account>"


$domainHost="<domain host name, such as litware for litwareinc.onmicrosoft.com>"
#Azure Active Directory
Connect-AzureAD
#SharePoint Online
Connect-SPOService -Url https://$domainHost-admin.sharepoint.com
#Skype for Business Online
$sfboSession = New-CsOnlineSession -UserName $acctName
Import-PSSession $sfboSession
For Exchange Online and the Security & Compliance Center, see the following topics to connect using multi-factor
authentication:
Connect to Exchange Online PowerShell using multi-factor authentication
Connect to Office 365 Security & Compliance Center PowerShell using multi-factor authentication
Note that in both cases, you must connect using separate sessions of the Exchange Online Remote PowerShell
Module.

New to Office 365?


TIP
New to Office 365?
Discover free video courses for Office 365 admins and IT pros, brought to you by LinkedIn Learning.

See also
Connect to Office 365 PowerShell
Manage SharePoint Online with Office 365 PowerShell
Manage user accounts and licenses with Office 365 PowerShell
Use Windows PowerShell to create reports in Office 365
Use Windows PowerShell to create reports in Office
365
2/8/2018 • 1 min to read • Edit Online

Summary: Use Office 365 PowerShell to create reports that you cannot produce in the Office 365 Admin center.
There are many different reports available in the Office 365 Admin center. However, these reports only provide so
much information and sometimes you need more. That's when you need Office 365 PowerShell
These articles that describe how to use Office 365 PowerShell to obtain information from your Office 365 tenant:
Getting started with reporting using Office 365 PowerShell:
Office 365 PowerShell can reveal additional information that you cannot see with the Admin center
Office 365 PowerShell is great at filtering data
Office 365 PowerShell makes it easy to print or save data
Reports for user accounts and licenses:
View licenses and services with Office 365 PowerShell
View licensed and unlicensed users with Office 365 PowerShell
View account license and service details with Office 365 PowerShell
View user accounts with Office 365 PowerShell
Reports for SharePoint Online:
Manage SharePoint Online users and groups with Office 365 PowerShell
Manage SharePoint Online site groups with Office 365 PowerShell
Reports for Exchange Online:
Display Exchange Online mailbox information with Office 365 PowerShell
Display Exchange Online reports with Office 365 PowerShell

See also
Manage Office 365 with Office 365 PowerShell
Getting started with Office 365 PowerShell
Manage SharePoint Online with Office 365 PowerShell
Manage user accounts and licenses with Office 365 PowerShell
Using Excel to Retrieve Office 365 Reporting Data
Using Excel to Retrieve Office 365 Reporting Data
2/13/2018 • 5 min to read • Edit Online

Summary: Use the oData feature in Microsoft Excel to retrieve detailed reporting information for your
deployment of Office 365
Reporting is a key part of system administration. The Office 365 Admin center includes a number of predefined
reports, which you can access from the Reports section of the left navigation. There are usage reports and security
and compliance reports.
The reports available to you depend on the version of Office 365 you are using and which Office 365 services you
have enabled. For more information, see the Reports page.
The pre-defined Admin center reports are an excellent resource. They make it easy to check on such things as
mailbox usage or the number of minutes that your users have been spending in online conferences. However, when
it comes to detailed analysis of your Office 365 domain, the reports do have their limitations.
One way to work around these limitations is to use Windows PowerShell or another development language to
access the Office 365 reporting service and create custom reports; custom reports give you the ability to dictate
which data (and how much data) is returned from the Office 365 reporting service. By writing custom reports you
can also specify how the data should be sorted and grouped, and, if applicable, how that data should be saved; for
example, you can save data in XML format or in a comma-separated values format that can easily be imported in
Excel.
In addition, custom scripts/applications enable you to access reports that are not available in the Office 365 Admin
center. For example, the Admin center can tell you how many stale mailboxes you have, but it can't tell which
mailboxes haven't been accessed in the past 30 days. That is something that a custom PowerShell script can tell
you. Taken together, this represents an enormous amount of flexibility in return for having to write a short and
relatively-simple Windows PowerShell script.

[!VISUAL BASIC NOTE ] For more information, see the home page for the Office 365 reporting service.

In order to retrieve this data, you do have to write code of some kind. That's worth it if you are a larger
organization that needs to limit the amount and the type of information that gets returned. But if you're a smaller
organization, and you don't need to limit the amount and type of information that gets returned, you might
consider opening the Office 365 reports from within Excel itself.
However, there are a few limitations here, the primary one being this: you cannot filter, sort, select, or otherwise
manipulate the data that before it gets returned. Instead, you simply get back the default set of data returned by the
report. In some cases that might not be enough data. For example, the report might return data for, say, only the
previous month and not for the entire year. Conversely, in other cases that might be too much data: you might get
back data for the entire year even though you only want data for the previous month.
To open an Office 365 report directly from within Excel, complete the following procedure:
1. Start by opening a new worksheet in Excel. On that worksheet, click Data, click From Other Sources, and
then click From OData Data Feed. That brings up the Data Connection Wizard dialog box:
2. On the Connect to a Data Feed page, enter
https://reports.office365.com/ecp/reportingwebservice/reporting.svc/ as the data feed location. Note
that you can only enter the base URL as shown; you cannot add any Select, Filter, or Format statements. If
you enter anything but the base URL you won't get back any data; instead, you'll simply see the following
error message:

3. After entering the reporting service URL, select Use this name and password under Log on credentials.
In the User Name box, enter your Office 365 logon name (for example,
[email protected]). In the Password box, enter your Office 365 logon password and then
click Next. Excel will then attempt to connect to the reporting service using the supplied credentials.
4. After you have been authenticated, you'll see the Select Tables page. Select the report that you'd like to
view (for example, MailTrafficTop ) and then click Next:
NOTE
It's possible to select multiple reports; that results in multiple tables/charts being added to your Excel spreadsheet. It's
even possible to create a single table/chart that combines data from multiple reports. However, we won't discuss that
in this introductory article.

5. After clicking Next you'll be presented with the Save Data Connection File and Finish page:
You don't have to enter any information here. All you need to do to retrieve your data is to click Finish.
However, it's worth noting that, by default, Excel saves information about each data connection you make;
this data is stored in your My Data Sources folder:

That's why the dialog box includes text boxes with labels like Friendly Name and Search Keywords; these
options give you the chance to customize these data connections. That way you do not end up with a whole
bunch of data sources that look like these:
DataFeed_1_reports-office365-com ClientSoftwareBrowserDetail.odc
DataFeed_1_reports-office365-com MailTrafficTop.odc
DataFeed_1_reports-office365-com Multiple Tables.odc
DataFeed_2_reports-office365-com MailboxActivityWeekly.odc
DataFeed_2_reports-office365-com MailTrafficTop.odc
DataFeed_3_reports-office365-com ClientSoftwareBrowserDetail.odc

If you select the checkbox Save password in file, you'll be able to reuse these data feeds. For example, suppose
you save a data connection as Client Browser Report. The next time you want information about the web
browsers being used to access your Office 365 domain you don't have to walk through the data connection wizard.
Instead, all you need to do is open Excel, click Data, and then click Existing Sources. Select the desired data
connection in the Existing Connections dialog box and then click OK:

At that point, Excel will make the connection for you and retrieve the data.
Note that these .ODC files are plain-text XML files. Included in these plain-text XML files are your Office 365 user
name and password:
<odc:ConnectionString>Data
Source=https://reports.office365.com/ecp/reportingwebservice/reporting.svc/;Namespaces to Include=;Max
Received Message Size=4398046511104;Integrated Security=Basic; **User
[email protected];Password=MYpassw0rd!*;Persist Security Info=false;Service Document
Url=https://reports.office365.com/ecp/reportingwebservice/reporting.svc/</odc:ConnectionString>
If you don't like the idea of saving your user name and password in a plain-text file, then don't check the box
labeled Save password in file. If you do that, however, keep in mind that you won't be able to reuse these data
connections. That's because, without the user name and password, Office 365 will not be able to authenticate your
attempt to log on to the service.
1. Click Finish on the Save Data Connection File and Finish page you'll be presented with the Import
Data dialog box:

2. Select your view options (for example, PivotTable Report ) and then click OK. If all goes well, your data will
be imported and be presented in whichever view option you happened to choose:

What you do with that data is then entirely up to you. For some suggestions. take a look at Create an Excel Services
dashboard using an oData data feed. Although that article doesn't use the Office 365 reporting service, it does
provide some handy hints for doing things like adding filters and slicers to your new dashboard.
See also
Manage Office 365 with Office 365 PowerShell
Getting started with Office 365 PowerShell
Use Windows PowerShell to create reports in Office 365
Cmdlet references for Office 365 services
5/18/2018 • 1 min to read • Edit Online

Summary: Find Office 365 PowerShell cmdlet reference topics for Azure Active Directory, Exchange Online,
SharePoint Online, Skype for Business Online, and Security & Compliance.
Cmdlet reference topics for the various Office 365 services provide detailed information and instructions on how
to use each cmdlet. Additionally, each Office 365 service that has PowerShell support requires different connection
instructions.

NOTE
To connect to all services at once, see Connect to all Office 365 services in a single Windows PowerShell window.

Azure Active Directory PowerShell cmdlets


The Azure Active Directory PowerShell for Graph cmdlet reference topics are located in the Reference section of
the Azure Active Directory PowerShell for Graph documentation.
The Azure Active Directory Module for Windows PowerShell cmdlet reference topics are located in the Reference
section of the Azure Active Directory (MSOnline) documentation.
For Office 365 PowerShell connection instructions, see Connect to Office 365 PowerShell.

Exchange Online PowerShell cmdlets


Exchange Online cmdlet reference topics are located in the Reference section of the Exchange Online PowerShell
documentation.
For connection instructions for Exchange Online PowerShell, click Connect to Exchange Online PowerShell.

NOTE
Reporting cmdlets for other services, for example, SharePoint Online, Skype for Business Online, and Office 365 user activity
are available in Exchange Online PowerShell. For more information, see Reporting cmdlets in Exchange Online.

SharePoint Online PowerShell cmdlets


For the SharePoint Online cmdlets, click Index of Windows PowerShell for SharePoint Online cmdlets.
For connection instructions for SharePoint Online PowerShell, click Set up the SharePoint Online Management
Shell Windows PowerShell environment.

Skype for Business Online PowerShell cmdlets


For Skype for Business Online cmdlet reference topics, click Skype for Business Online cmdlets.
For connection instructions for Skype for Business Online PowerShell, click Manage Skype for Business Online
with Office 365 PowerShell.
Security & Compliance Center PowerShell cmdlets
Office 365 Security & Compliance Center cmdlet reference topics are located in the Reference section of the
Exchange Online PowerShell documentation.
For connection instructions for Security & Compliance Center PowerShell, click Connect to the Office 365 Security
& Compliance Center PowerShell.

See also
Manage Office 365 with Office 365 PowerShell
Getting started with Office 365 PowerShell
Office 365 PowerShell community resources
2/13/2018 • 1 min to read • Edit Online

Summary: Get help for Office 365 PowerShell from these community venues.
Use these Yammer networks, community forums, and Wikis to get you connected to your peers and get your
Office 365 PowerShell questions answered quickly and correctly.
PowerShell for Office 365 group of the Office 365 Yammer Network
Manage Office 365 community forum
Exchange TechCenter community forum
Office Blogs
Manage Office 365 Wiki

See also
Manage Office 365 with Office 365 PowerShell
Getting started with Office 365 PowerShell
Manage user accounts and licenses with Office 365
PowerShell
2/13/2018 • 1 min to read • Edit Online

Summary: Learn how to manage user accounts and licenses with Office 365 PowerShell.
One of the primary tasks of any Office 365 administrator is managing user accounts and licenses. Although you
can accomplish some of these tasks in the Office 365 admin center, other tasks are much quicker and easier with
Office 365 PowerShell. For more information, see the following topics:
View licenses and services with Office 365 PowerShell
View licensed and unlicensed users with Office 365 PowerShell
Assign licenses to user accounts with Office 365 PowerShell
View account license and service details with Office 365 PowerShell
Assign roles to user accounts with Office 365 PowerShell
Disable access to services with Office 365 PowerShell
Remove licenses from user accounts with Office 365 PowerShell
Block user accounts with Office 365 PowerShell
Delete and restore user accounts with Office 365 PowerShell
Create user accounts with Office 365 PowerShell
View user accounts with Office 365 PowerShell
Configure user account properties with Office 365 PowerShell
View licenses and services with Office 365
PowerShell
4/23/2018 • 3 min to read • Edit Online

Summary: Explains how to use Office 365 PowerShell to view information about the licensing plans, services,
and licenses that are available in your Office 365 organization.
Every Office 365 subscription consists of the following elements:
Licensing plans These are also known aslicense plans or Office 365 plans. Licensing plans define the
Office 365 services that are available to users. Your Office 365 subscription may contain multiple licensing
plans. An example licensing plan would be Office 365 Enterprise E3.
Services These are also known asservice plans. Services are the Office 365 products, features, and
capabilities that are available in each licensing plan, for example, Exchange Online and Office Professional
Plus. Users can have multiple licenses assigned to them from different licensing plans that grant access to
different services.
Licenses Each licensing plan contains the number of licenses that you purchased. You assign licenses to
users so they can use the Office 365 services that are defined by the licensing plan. Every user account
requires at least one license from one licensing plan so they can log on to Office 365 and use the services.
You can use Office 365 PowerShell to view details about the available licensing plans, licenses, and services in
your Office 365 organization. For more information about the products, features, and services that are available
in different Office 365 subscriptions, see Office 365 Plan Options.

Before you begin


The procedures in this topic require you to connect to Office 365 PowerShell. For instructions, see
Connect to Office 365 PowerShell.
A PowerShell script is available that automates the procedures described in this topic. Specifically, the
script allows you to view and disable services in your Office 365 organization, including Sway. For more
information, see Disable access to Sway with Office 365 PowerShell.

View information about licensing plans and the available licenses


To view summary information about your current licensing plans and the available licenses for each plan, run the
following command in Office 365 PowerShell:

Get-MsolAccountSku

The results contain the following information:


AccountSkuId: Show the available licensing plans for your organization by using the syntax
<CompanyName>:<LicensingPlan> . is the value that you provided when you enrolled in Office 365, and is
unique for your organization. The value is the same for everyone. For example, in the value
litwareinc:ENTERPRISEPACK , the company name is litwareinc , and the licensing plan name
ENTERPRISEPACK , which is the system name for Office 365 Enterprise E3.

ActiveUnits: Number of licenses that you've purchases for a specific licensing plan.
WarningUnits: Number of licenses in a licensing plan that you haven't renewed, and that will expire after
the 30-day grace period.
ConsumedUnits: Number of licenses that you've assigned to users from a specific licensing plan.
To view details about the Office 365 services that are available in all of your license plans, run the following
command:

Get-MsolAccountSku | Select -ExpandProperty ServiceStatus

The following table shows the Office 365 service plans and their friendly names for the most common services.
Your list of service plans might be different. For a complete list of service plans and their friendly names, contact
Office Support.

SERVICE PLAN DESCRIPTION

SWAY Sway

TEAMS1 Microsoft Teams

YAMMER_ENTERPRISE Yammer

RMS_S_ENTERPRISE Azure Rights Management (RMS)

OFFICESUBSCRIPTION Office Professional Plus

MCOSTANDARD Skype for Business Online

SHAREPOINTWAC Office Online

SHAREPOINTENTERPRISE SharePoint Online

EXCHANGE_S_ENTERPRISE Exchange Online Plan 2

To view details about the Office 365 services that are available in a specific licensing plan, use the following
syntax.

(Get-MsolAccountSku | where {$_.AccountSkuId -eq "<AccountSkuId>"}).ServiceStatus

This example shows the Office 365 services that are available in the litwareinc:ENTERPRISEPACK (Office 365
Enterprise E3) licensing plan.

(Get-MsolAccountSku | where {$_.AccountSkuId -eq "litwareinc:ENTERPRISEPACK"}).ServiceStatus

New to Office 365?


TIP
New to Office 365?
Discover free video courses for Office 365 admins and IT pros, brought to you by LinkedIn Learning.

See also
View licensed and unlicensed users with Office 365 PowerShell
View account license and service details with Office 365 PowerShell
Get-MsolAccountSku
View licensed and unlicensed users with Office 365
PowerShell
2/13/2018 • 4 min to read • Edit Online

Summary: Explains how to use Office 365 PowerShell to view licensed and unlicensed user accounts.
User accounts in your Office 365 organization may have some, all, or none of the available licenses assigned to
them from the licensing plans that are available in your organization. You can use Office 365 PowerShell to
quickly find the licensed and unlicensed users in your organization.

Before you begin


The procedures in this topic require you to connect to Office 365 PowerShell. For instructions, see Connect
to Office 365 PowerShell.
If you use the Get-MsolUser cmdlet without using the -All parameter, only the first 500 accounts are
returned.

The short version (instructions without explanations)


This section presents the procedures without fanfare or superfluous explanation. If you have questions or want
more information, you can read rest of the topic.
To view the list of all user accounts and their licensing status in your organization, run the following command in
Office 365 PowerShell:

Get-MsolUser -All

To view the list of all unlicensed user accounts in your organization, run the following command:

Get-MsolUser -All -UnlicensedUsersOnly

To view the list of all licensed user accounts in your organization, run the following command:

Get-MsolUser -All | where {$_.isLicensed -eq $true}

The long version (instructions with detailed explanations)


Office 365 user accounts and Office 365 licenses don't need to have a one-to-one correspondence: it's possible to
have Office 365 users who do not have an Office 365 license, and it's possible to have Office 365 licenses that
haven't been assigned to a user. (In fact, a single user account can even have multiple Office 365 licenses.) When
you create a new Office 365 user account (see the article License Office 365 users with Windows PowerShell for
more information) you don't have to assign that user a license: the new user will have a valid account, but he or
she won't be able to sign in to Office 365. If they try to sign in, they'll see something similar to this:
Likewise, you might have a user who will be taking some extended time off, perhaps for a sabbatical or for
maternity/paternity leave. In a case like that, you could remove the user's license but leave the user account intact
(that is, leave all its property values, such as address and phone number, as-is). By doing that, you can assign their
license to someone else (like, say, a temporary worker filling in for the person on leave). When the user returns to
work you can issue them a new license and they'll be able to resume working as if they'd never been gone.
Which simply means that, yes, you can have users who have accounts but who don't have licenses. Or vice-versa.
The article View licenses and services with Office 365 PowerShell explains how you can determine the number of
Office 365 licenses your organization has purchased as well as how many of those licenses have been assigned to
users. That's important information. Equally important, however is knowing which of your users have been
assigned these licenses and which ones haven't. And this article will tell you how to do just that.
As you probably know, the Get-MsolUser cmdlet returns information about all your Office 365 user accounts.
Need some quick info about all your Office 365 users? Then run this command in Office 365 PowerShell:

Get-MsolUser

In turn, Get-MsolUser returns data similar to this:

UserPrincipalName DisplayName isLicensed


----------------- ----------- ----------
[email protected] Zrinka Makovac True
[email protected] Belinda Newman False
[email protected] Bonnie Kearney True
[email protected] Fabrice Canel True
[email protected] Anne Wallace True
[email protected] Alex Darrow True

As you can see, one of the property values returned is for the isLicensed property. If isLicensed is equal to
False that means that the user doesn't have a license for Office 365. In other words, and if you wanted to, you
could simply scroll through your list of users and pick out the ones where the isLicensed property is set to False
.
At any rate, scrolling through a list of users trying to pick out the unlicensed users works as long as you have a
relatively small number of users. If you have a large number of users, however, scrolling through that list will be, at
best, extremely tedious. (And, depending on how Windows PowerShell has been configured, perhaps downright
impossible. That's because there's a limit to the number of lines of output that can be displayed in the Windows
PowerShell console at any one time.)
With that in mind, a much better way to list your unlicensed users is to run this command instead:

Get-MsolUser -UnlicensedUsersOnly

That command returns only those users who don't have a license for Office 365. In other words:

UserPrincipalName DisplayName isLicensed


----------------- ----------- ----------
[email protected] Belinda Newman False

As you can see we have one unlicensed user. And what is we only wanted a list of the licensed users? That's a tiny
bit more complicated, but only the tiniest bit:

Get-MsolUser | Where-Object {$_.isLicensed -eq $true}

That command, which looks for all the user accounts where the isLicensed property is equal to True , returns
information similar to this:

UserPrincipalName DisplayName isLicensed


----------------- ----------- ----------
[email protected] Zrinka Makovac True
[email protected] Bonnie Kearney True
[email protected] Fabrice Canel True
[email protected] Anne Wallace True
[email protected] Alex Darrow True

As you can see, information is not returned for Belinda Newman. Why not? You got it: because the isLicensed
property for Belinda's account is not set to True .

See also
For more information about the cmdlets that are used in these procedures, see the following topics:
Get-MsolUser
Where-Object
Assign licenses to user accounts with Office 365
PowerShell
4/19/2018 • 11 min to read • Edit Online

Summary: Explains how to use Office 365 PowerShell assign an Office 365 license to unlicensed users.
Licensing user accounts in Office 365 is important, because users can't use any Office 365 services until their
account has been licensed. You can use Office 365 PowerShell to efficiently assign licenses to unlicensed accounts,
especially multiple accounts.

Before you begin


The procedures in this topic require you to connect to Office 365 PowerShell. For instructions, see Connect
to Office 365 PowerShell.
Use the Get-MsolAccountSku cmdlet to view the available licensing plans and the number of available
licenses in each plan in your organization. The number of available licenses in each plan is ActiveUnits -
WarningUnits - ConsumedUnits. For more information about licensing plans, licenses, and services, see
View licenses and services with Office 365 PowerShell.
To find the unlicensed accounts in your organization, run the command
Get-MsolUser -All -UnlicensedUsersOnly

You can assign licenses only to user accounts that have the UsageLocation property set to a valid ISO
3166-1 alpha-2 country code. For example, US for the United States, and FR for France. Some Office 365
services aren't available in certain countries. For more information, see About license restrictions.
To find accounts that don't have a UsageLocation value, run the command
Get-MsolUser -All | where {$_.UsageLocation -eq $null} . To set the UsageLocation value on an account,
use the syntax Set-MsolUser -UserPrincipalName "<Account>" -UsageLocation <CountryCode> . For example,
Set-MsolUser -UserPrincipalName "[email protected]" -UsageLocation US .

If you use the Get-MsolUser cmdlet without using the -All parameter, only the first 500 accounts are
returned.

The short version (instructions without explanations)


This section presents the procedures without detailed explanation. If you have questions or want more
information, you can read rest of the topic.
To assign a license to a user, use the following syntax in Office 365 PowerShell:

Set-MsolUserLicense -UserPrincipalName "<Account>" -AddLicenses "<AccountSkuId>"

This example assigns a license from the litwareinc:ENTERPRISEPACK (Office 365 Enterprise E3) licensing plan to
the unlicensed user [email protected] .

Set-MsolUserLicense -UserPrincipalName "[email protected]" -AddLicenses "litwareinc:ENTERPRISEPACK"

To assign a license to many unlicensed users, use the following syntax:


$x = Get-MsolUser -All -UnlicensedUsersOnly [<FilterableAttributes>]; $x | foreach {Set-MsolUserLicense -
AddLicenses "<AccountSkuId>"}

Notes
You can't assign multiple licenses to a user from the same licensing plan.
If you don't have enough available licenses, the licenses are assigned to users in the order that they're
returned by the Get-MsolUser cmdlet until the available licenses run out.
This example assigns licenses from the litwareinc:ENTERPRISEPACK (Office 365 Enterprise E3) licensing plan to all
unlicensed users.

$AllUn = Get-MsolUser -All -UnlicensedUsersOnly; $AllUn | foreach {Set-MsolUserLicense -AddLicenses


"litwareinc:ENTERPRISEPACK"}

This example assigns those same licenses to unlicensed users in the Sales department in the United States.

$USSales = Get-MsolUser -All -Department "Sales" -UsageLocation "US" -UnlicensedUsersOnly; $USSales | foreach
{Set-MsolUserLicense -AddLicenses "litwareinc:ENTERPRISEPACK"}

The long version (instructions with detailed explanations)


As noted in the article View licensed and unlicensed users with Office 365 PowerShell, it's possible to have users
who have valid Office 365 user accounts, but who have not been issued an Office 365 license. That means that,
valid account or no valid account, those users will not be able to log on to Office 365. And if you can't log on, you
can't take advantage of any Office 365 services.
The aforementioned article also noted that we can return a list of unlicensed user accounts by running this
command:

Get-MsolUser -All -UnlicensedUsersOnly

That command returns information about any users who are not currently licensed for Office 365:

UserPrincipalName DisplayName isLicensed


----------------- ----------- ----------
[email protected] Belinda Newman False

As you can see, we have one unlicensed user: Belinda Newman. So how do we go about assigning Belinda an
Office 365 license?
For starters, we're going to run the Get-MsolAccountSku cmdlet discussed in the article View licenses and
services with Office 365 PowerShell:

Get-MsolAccountSku

That command returns data similar to this:


AccountSkuId ActiveUnits WarningUnits ConsumedUnits
------------ ----------- ------------ -------------
litwareinc:ENTERPRISEPACK 25 0 24

Why did we run Get-MsolAccountSku ? ("Sku," in case you're wondering, is short for "stock-keeping unit." For
our purposes, that's just business-speak for "product.") There are two reasons why we ran Get-MsolAccountSku.
First, we need to make sure we actually have a license to assign Belinda. Do we have any licenses we can assign
her? To determine that, we take the value of ActiveUnits property (25) and subtract the values of the
WarningUnits (0) and ConsumedUnits (24) properties:
25 - 0 - 24 = 1

The ActiveUnits property tells us how many licenses we've purchased, and the combined value of
WarningUnits and ConsumedUnits tells us how many licenses are currently in use. If we subtract the number
of licenses already spoken for from the number of licenses we purchased, we'll know how many licenses are still
available. As luck would have it, we have one license available for distribution:
25 - 0 - 24 = 1

Second, in order to assign Belinda a new license we need to know the name of our licensing plan (that is, we need
to know the AccountSkuId ). In this case, that's easy: we only have a single licensing plan (
litwareinc:ENTERPRISEPACK ). Note, however, that it's possible for an organization to have multiple licensing plans.
In that case, Get-MsolAccountSku would return two different AccountSkuIds, and you would need to pick the
appropriate licensing plan when assigning licenses. For now, though, we're going to stick with the simplest case,
and assume we have just one licensing plan.
So then how do we assign Belinda Newman a new license? Like this:

Set-MsolUserLicense -UserPrincipalName "[email protected]" -AddLicenses "litwareinc:ENTERPRISEPACK"

That's also you have to do: just call the Set-MsolUserLicense cmdlet, making sure that you specify the
UserPrincipalName parameter for the user and the appropriate licensing plan.
When Set-MsolUserLicense finishes running, you'll see something similar to this onscreen:
PS C:\windows\system32>

In other words, it won't look like anything has happened. To verify that the user has been assigned a license, run a
command like the following:

Get-MsolUser -UserPrincipalName "[email protected]"

If everything worked as expected, you should see that Belinda's isLicensed property is now set to True:

UserPrincipalName DisplayName isLicensed


----------------- ----------- ----------
[email protected] Belinda Newman True

[!SECURITY NOTE ] Good question: what if you made a mistake and tried to assign a license to a user who
already has a license? Will you end up giving two licenses to a single user? > The quick answer? No; Office
365 won't let you assign more than one license to the same user. (Well, more than one license from the same
licensing plan, that is.) If you try to do that your command will fail with the following error message: >
Set-MsolUserLicense : Unable to assign this license because it is invalid. Use the Get-MsolAccountSku
cmdlet to retrieve a list of valid licenses.
> Admittedly, that error message is a tiny bit misleading: the license isn't really invalid, it's just being assigned
to a user who already has a license. But, error message aside, the important thing is that one user won't end
up with multiple licenses.

As you've just seen, it's very easy to use Office 365 PowerShell to assign a single license to a single user. And that
leads to an obvious question: wouldn't it be just as easy, maybe even easier, to use the Office 365 admin center to
assign a single license to a single user? Well, maybe; that depends, in part, on whether you're more comfortable
using Windows PowerShell or more comfortable using the Office 365 admin center. Where Windows PowerShell
really shines, however, is when you need to assign multiple licenses to multiple users. For example, this command
assigns an Office 365 license to any of your users that don't already have a license:

Get-MsolUser -All -UnlicensedUsersOnly | Set-MsolUserLicense -AddLicenses "litwareinc:ENTERPRISEPACK"

In the preceding command, we use Get-MsolUser and the UnlicensedUsersOnly parameter to return a collection
of all the unlicensed user accounts. We then pass that collection to the Set-MsolUserLicense cmdlet; in turn, Set-
MsolUserLicense assigns a license (taken from the litwareinc:ENTERPRISEPACK licensing plan) to each user in the
collection.
Ah, but what if you have 5 unlicensed users but only one available license? In that case Set-MsolUserLicense will
give the available license to the first user returned by Get-MsolUser. Set-MsolUserLicense will then dutifully try
to assign a license to the other four users, but all four of those attempts will fail along with the following error
message:
Set-MsolUserLicense : Unable to assign this license because the number of allowed licenses have been assigned.

In other words, Set-MsolUserLicense won't just fail. Instead, it will assign as many licenses as it can. Only then will
it fail.
Let's try another example. Maybe you'd like to assign a license to all the users in the Sales department. No
problem:

Get-MsolUser -All -Department "Sales" | Set-MsolUserLicense -AddLicenses "litwareinc:ENTERPRISEPACK"

Or, if you want to get really fancy, and if you want to keep error messages and computing processing to a
minimum, just assigned a license to unlicensed users from the Sales department:

Get-MsolUser -All -Department "Sales" -UnlicensedUsersOnly | Set-MsolUserLicense -AddLicenses


"litwareinc:ENTERPRISEPACK"

After all, there's no point trying to license users who already have a license. As we've already seen, that won't
work.
Here's another example. Maybe you'd like to license all the US users who don't currently have an Office 365
license. In that case:

Get-MsolUser -All -UsageLocation "US" -UnlicensedUsersOnly | Set-MsolUserLicense -AddLicenses


"litwareinc:ENTERPRISEPACK"

And so on and so on.


NOTE
How long does it take to run a command that, say, issues licenses to all your unlicensed users? That's difficult to say: it
depends on everything from the number of users you have to the speed of your network connection. If you have a couple
hundred users to license this will go reasonably quickly (that is, it shouldn't take more than a minute or two). If you have
10,000 users to license it will obviously take a little longer. But nowhere near as long as it would take to assign licenses to
10,000 users by using the Office 365 admin center.

As long as we're on the subject, here's something you need to watch out for when assigning licenses: if a user does
not have a value configured for the UsageLocation property you won't be able to assign that user an Office 365
license. Instead, you'll get an error message similar to this:
Set-MsolUserLicense : You must provide a required property: Parameter name: UsageLocation

In somewhat-roundabout fashion, this error message tells us that the user in question has not been assigned a
UsageLocation. As you might have guessed, the UsageLocation property (which indicates the region or
country where the user typically uses Office 365) is extremely important. Why? That's because the services
available to a user depend not only on the licensing pack that you purchased but also on where the user lives: due
to local rules and regulations, some services might not be available to some users. If a user doesn't have a
UsageLocation, Office 365 has no way of knowing which services can legally be exposed to that user. Therefore,
Office 365 can't offer any services to that user, at least not until the UsageLocation has been specified.

NOTE
When you configure a user account you'll know immediately if there are any license restrictions associated with the specified
part of the world. For example, if you change the UsageLocation for a licensed user to Iran ( IR ), the command will fail
with this error message:
Set-MsolUser : Unable to update license for this user. One or more of the assigned service plans is not
available in this user's country. Prohibited Service Plans: EXCHANGE_S_ENTERPRISE, SHAREPOINTENTERPRISE,
SHAREPOINTWAC, MCOSTANDARD, OFFICESUBSCRIPTION, RMS_S_ENTERPRISE. Specific service plans can be disabled
for a user by using the licenseoptions parameter.
> That's because Office 365 is not currently available to users in Iran. For more information, see About license restrictions.
Incidentally, Office 365 uses the two-letter country codes produced by the International Organization for Standardization
(ISO). You can find those codes on the ISO web site.

If you want to verify that a given user has a UsageLocation you can use a command similar to this one:

Get-MsolUser -UserPrincipalName "[email protected]" | Select-Object UsageLocation

Alternatively, you can return a list of all the users who don't have a UsageLocation by using this command:

Get-MsolUser -All | Where-Object {$_.UsageLocation -eq $null}

NOTE
When you assign a license to a user that user will, by default, be given access to all the Office 365 services that your
organization has access to. For example, if you purchased licenses for Office 365 Enterprise E3, your newly-licensed user will
automatically be granted access to services like Exchange Online, Skype for Business Online, and SharePoint Online. If you
would prefer to limit a user's access to those services (for example, you might want a user to have access to SharePoint
Online but not to Exchange Online and Skype for Business Online) then see the article Disable access to services with Office
365 PowerShell.
New to Office 365?
TIP
New to Office 365?
Discover free video courses for Office 365 admins and IT pros, brought to you by LinkedIn Learning.

See Also
See the following additional topics about managing users with Office 365 PowerShell:
Create user accounts with Office 365 PowerShell
Delete and restore user accounts with Office 365 PowerShell
Block user accounts with Office 365 PowerShell
Remove licenses from user accounts with Office 365 PowerShell
For more information about the cmdlets that are used in these procedures, see the following topics:
Get-MsolAccountSku
Get-MsolUser
Set-MsolUserLicense
ForEach-Object
Select-Object
Where-Object
View account license and service details with Office
365 PowerShell
4/19/2018 • 12 min to read • Edit Online

Summary: Explains how to use Office 365 PowerShell to determine the Office 365 services that have been
assigned to users.
In Office 365, licenses from licensing plans (also called SKUs or Office 365 plans) give users access to the Office
365 services that are defined for those plans. However, a user might not have access to all the services that are
available in a license that's currently assigned to them. You can use Office 365 PowerShell to view the status of
services on user accounts.

Before you begin


The procedures in this topic require you to connect to Office 365 PowerShell. For instructions, see Connect
to Office 365 PowerShell.
Use the commands Get-MsolAccountSku and
(Get-MsolAccountSku | where {$_.AccountSkuId -eq '<AccountSkuId>'}).ServiceStatus to find the following
information:
The licensing plans that are available in your organization.
The services that are available in each licensing plan, and the order in which they are listed (the index
number).
For more information about licensing plans, license, and services, see View licenses and services
with Office 365 PowerShell.
Use the command Get-MsolUser -UserPrincipalName <user account UPN> | Format-List DisplayName,Licenses
to find the licenses that are assigned to a user, and the order in which they are listed (the index number).
If you use the Get-MsolUser cmdlet without using the All parameter, only the first 500 accounts are
returned.

The short version (instructions without explanations)


To view all the Office 365 PowerShell services that a user has access to, use the following syntax:

(Get-MsolUser -UserPrincipalName <user account UPN>).Licenses[<LicenseIndexNumber>].ServiceStatus

This example shows the services to which the user [email protected] has access. This shows the services
that are associated with all licenses that are assigned to her account.

(Get-MsolUser -UserPrincipalName [email protected]).Licenses.ServiceStatus

This example shows the services that user [email protected] has access to from the first license that's
assigned to her account (the index number is 0).
(Get-MsolUser -UserPrincipalName [email protected]).Licenses[0].ServiceStatus

To find all the licensed users who have been enabled or not enabled for specific services, use the following syntax:

Get-MsolUser -All | where {$_.isLicensed -eq $true -and $_.Licenses[<LicenseIndexNumber>


].ServiceStatus[<ServiceIndexNumber> ].ProvisioningStatus <-eq | -ne> "Disabled" -and
$_.Licenses[<LicenseIndexNumber> ].ServiceStatus[<ServiceIndexNumber> ].ProvisioningStatus <-eq | -ne>
"Disabled"...}

These examples use the following information:


The license that gives access to the Office 365 services that we're interested in is the first license that's
assigned to all users (the index number is 0).
The Office 365 services that we're interested in are Skype for Business Online and Exchange Online. For
the licenses that are associated with the licensing plan, Skype for Business Online is the 6th service listed
(the index number is 5), and Exchange Online is the 9th service listed (the index number is 8).

This example returns all licensed users who are enabled for Skype for Business Online and Exchange Online.

Get-MsolUser -All | where {$_.isLicensed -eq $true -and $_.Licenses[0].ServiceStatus[5].ProvisioningStatus -ne


"Disabled" -and $_.Licenses[0].ServiceStatus[8].ProvisioningStatus -ne "Disabled"}

This example returns all licensed users who aren't enabled for Skype for Business Online or Exchange Online.

Get-MsolUser -All | where {$_.isLicensed -eq $true -and $_.Licenses[0].ServiceStatus[5].ProvisioningStatus -eq


"Disabled" -and $_.Licenses[0].ServiceStatus[8].ProvisioningStatus -eq "Disabled"}

The long version (instructions with detailed explanations)


Find the Office 365 PowerShell services that a user has access to
It's obviously important for you to know which users have been issued Office 365 licenses and which users
haven't. (See the article View licensed and unlicensed users with Office 365 PowerShell for more information).
However, simply having an Office 365 license doesn't tell you anything about what that user can actually do with
Office 365. Can he or she use Exchange Online or Skype for Business Online? Can this user access SharePoint
Online? Does he or she have access to Office Professional Plus? Having a license simply means that the user has
the potential to access these services. However, the capabilities available to a user depend on the services that
have been enabled on his or her license.
So how can we determine which Office 365 features a user has access to? To do that we need to run a command
similar to this one:

Get-MsolUser -UserPrincipalName [email protected] | Select-Object -ExpandProperty Licenses | Select-


Object -ExpandProperty ServiceStatus

In this command, we're using the Get-MsolUser cmdlet to return information about the account
[email protected]. Once we've returned that information, we then pipe the account data to the Select-
Object cmdlet and ask Select-Object to "expand" the value of the Licenses property:
Select-Object -ExpandProperty Licenses

Why do we do that? Well, by default the Licenses property only tells us the name of the licensing pack where
Belinda's license came from:
Licenses
--------
{litwareinc:ENTERPRISEPACK}

"Expanding" the Licenses property gives us a little more information:

ExtensionData AccountSku AccountSkuId ServiceStatus


------------- ---------- ------------ -------------
System.Runtime... Microsoft.On... litwarein... {Microsoft.Online.A...

And then by expanding the ServiceStatus property we can get back even more information:

*SERVICE PLAN* *DESCRIPTION*

SWAY Sway

TEAMS1 Microsoft Teams

YAMMER_ENTERPRISE Yammer

RMS_S_ENTERPRISE Azure Rights Management (RMS)

OFFICESUBSCRIPTION Office Professional Plus

MCOSTANDARD Skype for Business Online

SHAREPOINTWAC Office Online

SHAREPOINTENTERPRISE SharePoint Online

EXCHANGE_S_ENTERPRISE Exchange Online Plan 2

NOTE
You say that's too much typing? Well, if you can put up with a little Windows PowerShell obtuseness, you can run this
condensed version of the command instead: >
(Get-MsolUser -UserPrincipalName [email protected]).Licenses[0].ServiceStatus

In case you're wondering, we can "expand" the Licenses property because Licenses is a multivalued property: it's
a single property that can store multiple values. When we expand a property value we simply drill down to get at
these additional values that, by default, are not displayed onscreen.

NOTE
So how are you supposed to know that a value is a multivalued property? Well, to find that out, try running a command
similar to this: > Get-MsolUser -UserPrincipalName [email protected] | Get-Member > The Get-member
cmdlet returns information about the object itself; in this case, information about the property values that make up a user
account object. Here's what Get-Member has to say about the Licenses property:>
Licenses Property System.Collections.Generic.List[Microsoft.On... > If the property definition says something
about collections (in this case, System.Collections.Generic.List ) then you know you're dealing with a multivalued
property.
So what does all this mean? To answer that, let's first take another look at the information returned by the Get-
MsolUser cmdlet:

ServicePlan ProvisioningStatus
----------- ------------------
SWAY Success
INTUNE_O365 Success
YAMMER_ENTERPRISE PendingInput
RMS_S_ENTERPRISE Success
OFFICESUBSCRIPTION Success
MCOSTANDARD Success
SHAREPOINTWAC Success
SHAREPOINTENTERPRISE Success
EXCHANGE_S_ENTERPRISE Success

And let's also take a look at a table that explains what these oddly-named service plans really represent:

*SERVICE PLAN* *DESCRIPTION*

SWAY Sway

TEAMS1 Microsoft Teams

YAMMER_ENTERPRISE Yammer

RMS_S_ENTERPRISE Azure Rights Management (RMS)

OFFICESUBSCRIPTION Office Professional Plus

MCOSTANDARD Skype for Business Online

SHAREPOINTWAC Office Online

SHAREPOINTENTERPRISE SharePoint Online

EXCHANGE_S_ENTERPRISE Exchange Online Plan 2

Got all that? MCOSTANDARD is just an internal programming name for Skype for Business Online, while
OFFICESUSBCRIPTION is just the internal programming name for Office Professional Plus. It's not the most intuitive
thing in the world, but as long as you keep this table handy you won't have many problems when it comes to
working with Office 365 services.
But wait: there's more. As we learned in the article View licenses and services with Office 365 PowerShell, if the
ProvisioningStatus is set to Success that means that the service has been fully enabled; for example if
MCOSTANDARD is set to Success that means that the user can access Skype for Business Online. If the
ProvisioningStatus is set to PendingInput that means that Office 365 is still processing the service request;
however, the user can typically log on and access the service while the request finishes processing. (
YAMMER_ENTERPRISE will always be shown as PendingInput , but that's OK: that won't stop a user from logging on to
Yammer).
IMPORTANT
Users can install and activate a new Office Professional Plus installation while OFFICESUBSCRIPTION is in the PendingInput
state.

And, needless to say, is a service is set to Disabled that means that the service in question is not available to the
user.
Find users that have access to specific Office 365 PowerShell services
In a separate article, we saw how you can use Office 365 PowerShell to disable user access to services. (If you
missed that article, see Disable access to services with Office 365 PowerShell). That leads to an obvious question:
is there any way to determine which users (that is, more than one user) have which services enabled or disabled?
We were hoping that someone would ask that. In order to answer that question, let's review the table of services
that we first looked at in the article View licenses and services with Office 365 PowerShell for our only available
licensing plan litwareinc:ENTERPRISEPACK :

*SERVICE PLAN* *DESCRIPTION*

SWAY Sway

TEAMS1 Microsoft Teams

YAMMER_ENTERPRISE Yammer

RMS_S_ENTERPRISE Azure Rights Management (RMS)

OFFICESUBSCRIPTION Office Professional Plus

MCOSTANDARD Skype for Business Online

SHAREPOINTWAC Office Online

SHAREPOINTENTERPRISE SharePoint Online

EXCHANGE_S_ENTERPRISE Exchange Online Plan 2

As you might recall, the service plan is nothing more than the internal programming name for a product; for
example, OFFICESUBSCRIPTION , to name one, is the internal programming name for Office Professional Plus. If
OFFICESUBSCRIPTION shows up as SUCCESS on a user's service plan, then that means that the user is allowed to
access Office Professional Plus. If EXCHANGE_S_ENTERPRISE is listed as DISABLED that means the user can't use
Exchange Online.

IMPORTANT
Users can install and activate a new Office Professional Plus installation while OFFICESUBSCRIPTION is in the PendingInput
state.

Now is the time where the order in which the services appear is extremely important. Windows PowerShell
assigns an index number to each entry in the list. The first entry is 0, the next entry is 1, and so on. The results are
explained in the following table:
*INDEX NUMBER* *SERVICE PLAN*

0 SWAY

1 INTUNE_O365

2 YAMMER_ENTERPRISE

3 RMS_S_ENTERPRISE

4 OFFICESUBSCRIPTION

5 MCOSTANDARD

6 SHAREPOINTWAC

7 SHAREPOINTENTERPRISE

8 EXCHANGE_S_ENTERPRISE

As you can see, SWAY is the first service listed, so it gets assigned index number 0.
Cau t i on

Why 0 and not 1? That's a programming thing. In programming languages indices tell you how far an item is
"offset" from the beginning of the array. The first item is the beginning of the array, so its offset is 0. The second
item is 1 item from the beginning of the array, so its offset is 1.
Let's try an example. Suppose we'd like a list of all the licensed users who have not been enabled for Exchange
Online. To do that, we can use the following command:

Get-MsolUser | Where-Object {$_.isLicensed -eq $true -and $_.Licenses[0].ServiceStatus[8].ProvisioningStatus -


eq "Disabled"}

Admittedly, that's a cryptic-looking little command, so let's take a minute to explain how it works. This is actually a
two-part command, and the first part is very simple: we use the Get-MsolUser cmdlet to return a collection of all
our Office 365 users (both licensed and unlicensed):

Get-MsolUser

That information is then piped to the Where-Object cmdlet. Where-Object goes through all the user accounts
and looks for those accounts that meet both of the following criteria:
The isLicensed property is equal to ( -eq ) True ( $true ). That enables us to weed out the unlicensed
users.
The value of the Licenses[0].ServiceStatus[8].ProvisioningStatus property is equal to ( -eq ) Disabled
. For our immediate purposes, the important part of this unwieldy property name is this:
ServiceStatus[8]

The [8] represents the index number for Exchange Online. (We know that from looking at the table a few
minutes ago). What if we wanted to find all the users enabled for Skype for Business Online? Well, the
index number for Skype for Business Online is 5, so we'd use this syntax:
ServiceStatus[5]

Etc., etc.
Incidentally, Licenses[0] indicates the licensing plan that we want to look at. Since our test domain only
has one licensing plan this doesn't matter much. But suppose we had a user who has been assigned
licenses from two different licensing plans. In that case, Licenses[0] would represent the first licensing
plan, and Licenses[1] would represent the second licensing plan.
To find the licenses that are assigned to a user, and the order in which they are listed, run the following
command:

Get-MsolUser -UserPrincipalName <Account> | Format-List DisplayName,Licenses

Do you see how this all works? The index number for Office Professional Plus is 4; therefore, this command
returns a list of all the users who have not been enabled for Office Professional Plus:

Get-MsolUser | Where-Object {$_.isLicensed -eq $true -and $_.Licenses.ServiceStatus[4].ProvisioningStatus -eq


"Disabled"}

And what if we wanted a list of users who have been enabled for Office Professional Plus? Well, if you've been
enabled then your ServiceStatus will either be PendingInput or Success ; in other words, your ServiceStatus
will not equal ( -ne ) Disabled . That means all we have to do is take our previous command and swap out the
-eq operator for the -ne operator:

Get-MsolUser | Where-Object {$_.isLicensed -eq $true -and $_.Licenses.ServiceStatus[4].ProvisioningStatus -ne


"Disabled"}

As the saying goes, that code probably won't win many beauty contests. And, truth be told, the code can get even
more tangled. For example, suppose we want to look for users who have been enabled for both Skype for
Business Online and Exchange Online:

Get-MsolUser | Where-Object {$_.isLicensed -eq $true -and $_.Licenses.ServiceStatus[5].ProvisioningStatus -ne


"Disabled" -and $_.Licenses.ServiceStatus[8].ProvisioningStatus -ne "Disabled"}

But don't worry too much about how gnarly that might look: the important thing is that, with relatively little effort,
you can retrieve this information. Can't you get at this same information using the Office 365 admin center? In
theory, yes but, in practical terms, no. To get at this same information using the Office 365 admin center you'd
need to look at the licensing information for each user, one user at a time, and then manually keep track of who'd
been enabled for X and who hadn't. That would work, but let's be honest: if you have more than 10 or 11 users,
you're not going to do this. It's way too tedious and time-consuming.
Which, of course, is why we have Windows PowerShell: Windows PowerShell helps save you from tedious and
time-consuming tasks such as that.
Here's an example of a command for viewing service information for a specified set of services as identified by
their Licenses and ServiceStatus indexes for an Office 365 E5 subscription:
Get-MsolUser | Select-Object DisplayName, @{Name="Sway";Expression=
{$_.Licenses[0].ServiceStatus[12].ProvisioningStatus}}, @{Name="Teams";Expression=
{$_.Licenses[0].ServiceStatus[7].ProvisioningStatus}}, @{Name="Yammer";Expression=
{$_.Licenses[0].ServiceStatus[20].ProvisioningStatus}}, @{Name="AD RMS";Expression=
{$_.Licenses[0].ServiceStatus[19].ProvisioningStatus}}, @{Name="OfficePro";Expression=
{$_.Licenses[0].ServiceStatus[21].ProvisioningStatus}}, @{Name="Skype";Expression=
{$_.Licenses[0].ServiceStatus[22].ProvisioningStatus}}, @{Name="SharePoint";Expression=
{$_.Licenses[0].ServiceStatus[24].ProvisioningStatus}}, @{Name="Exchange";Expression=
{$_.Licenses[0].ServiceStatus[23].ProvisioningStatus}} | ConvertTo-CSV > "C:\Service Info.csv"

This command creates a CSV file showing all of your users and their service statuses for a specified set of services
(Teams, Yammer, AD RMS, OfficePro, Skype, SharePoint, and Exchange).

NOTE
You can get the list of services in a subscription from the
(Get-MsolUser -UserPrincipalName <user account UPN>).Licenses[<LicenseIndexNumber>].ServiceStatus command.
In the output, you start numbering the service indexes with 0. The preceding command is just an example. Index numbers
for services can change over time.

See also
See the following additional topics about managing users with Office 365 PowerShell:
Create user accounts with Office 365 PowerShell
Delete and restore user accounts with Office 365 PowerShell
Block user accounts with Office 365 PowerShell
Assign licenses to user accounts with Office 365 PowerShell
Remove licenses from user accounts with Office 365 PowerShell
For more information about the cmdlets that are used in these procedures, see the following topics:
ConvertTo-Html
Format-List
Get-MsolUser
Select-Object
Where-Object

New to Office 365?


TIP
New to Office 365?
Discover free video courses for Office 365 admins and IT pros, brought to you by LinkedIn Learning.
Assign roles to user accounts with Office 365
PowerShell
4/23/2018 • 3 min to read • Edit Online

Summary: Use Office 365 PowerShell and the Add-MsolRoleMember cmdlet to assign roles to user accounts.
You can quickly and easily assign roles to user accounts using Office 365 PowerShell by identifying the user
account's display name and the role name.

Before you begin


The procedures in this topic require you to connect to Office 365 PowerShell using a global administrator account.
For instructions, see Connect to Office 365 PowerShell.

For a single role change


Determine the following:
The user account that you want to configure.
To specify the user account, you must determine its Display Name. To get a complete list accounts, use this
command:

Get-MsolUser -All | Sort DisplayName | Select DisplayName | More

This command lists the Display Name of your user accounts, sorted by the Display Name, one screen at a
time. You can filter the list to a smaller set by using the Where cmdlet. Here is an example:

Get-MsolUser | Where DisplayName -like "John*" | Sort DisplayName | Select DisplayName | More

This command lists only the user accounts for which the Display Name starts with "John".
The role you want to assign.
To display the list of available roles that you can assign to user accounts, use this command:

Get-MsolRole | Sort Name | Select Name,Description

Once you have determined the Display Name of the account and the Name of the role, use these commands to
assign the role to the account:

$dispName="<The Display Name of the account>"


$roleName="<The role name you want to assign to the account>"
Add-MsolRoleMember -RoleMemberEmailAddress (Get-MsolUser | Where DisplayName -eq $dispName).UserPrincipalName
-RoleName $roleName

Copy the commands and paste them into Notepad. For the $dispName and $roleName variables, replace the
description text with their values, remove the < and > characters, and leave the quotes. Copy the modified lines
and paste them into your Windows Azure Active Directory Module for Windows PowerShell window to run them.
Alternately, you can use the Windows PowerShell Integrated Script Environment (ISE ).
Here is an example of a completed command set:

$dispName="Scott Wallace"
$roleName="SharePoint Service Administrator"
Add-MsolRoleMember -RoleMemberEmailAddress (Get-MsolUser | Where DisplayName -eq $dispName).UserPrincipalName
-RoleName $roleName

For multiple role changes


Determine the following:
Which user accounts that you want to configure.
To specify the user account, you must determine its Display Name. To get a list accounts, use this command:

Get-MsolUser -All | Sort DisplayName | Select DisplayName | More

This command lists the Display Name of all your user accounts, sorted by the Display Name, one screen at
a time. You can filter the list to a smaller set by using the Where cmdlet. Here is an example:

Get-MsolUser | Where DisplayName -like "John*" | Sort DisplayName | Select DisplayName | More

This command lists only the user accounts for which the Display Name starts with "John".
Which roles you want to assign to each user account.
To display the list of available roles that you can assign to user accounts, use this command:

Get-MsolRole | Sort Name | Select Name,Description

Next, create a comma-separated value (CSV ) text file that contains the DisplayName and role Name fields. Here is
an example:

DisplayName,RoleName
"Belinda Newman","Billing Administrator"
"John Doe","SharePoint Service Administrator"
"Alice Smithers","Lync Service Administrator"

Next, fill in the location of the CSV file and run the resulting commands at the PowerShell command prompt.

$fileName="<path and file name of the input CSV file that contains the role changes, example:
C:\admin\RoleUpdates.CSV>"
$roleChanges=Import-Csv $fileName | ForEach {Add-MsolRoleMember -RoleMemberEmailAddress (Get-MsolUser | Where
DisplayName -eq $_.DisplayName).UserPrincipalName -RoleName $_.RoleName }

See also
Manage user accounts and licenses with Office 365 PowerShell
Manage Office 365 with Office 365 PowerShell
Getting started with Office 365 PowerShell
Add-MsolRoleMember
Disable access to services with Office 365 PowerShell
2/15/2018 • 5 min to read • Edit Online

Summary: Explains how to use Office 365 PowerShell to disable access to Office 365 services for users in your
organization.
When an Office 365 account is assigned a license from a licensing plan, Office 365 services are made available to
the user from that license. However, you can control the Office 365 services that the user can access. For example,
even though the license allows access to SharePoint Online, you can disable access to it. In fact, you can use Office
365 PowerShell to disable access to any number of services for:
An individual account.
A group of accounts.
All accounts in your organization.

Before you begin


The procedures in this topic require you to connect to Office 365 PowerShell. For instructions, see Connect
to Office 365 PowerShell.
You use the Get-MsolAccountSku cmdlet to view your available licensing plans, and the Office 365
services that are available in those plans. For more information, see View licenses and services with Office
365 PowerShell.
To see the before and after results of the procedures in this topic, see View account license and service
details with Office 365 PowerShell.
A PowerShell script is available that automates the procedures described in this topic. Specifically, the script
allows you to view and disable services in your Office 365 organization, including Sway. For more
information, see Disable access to Sway with Office 365 PowerShell.
If you use the Get-MsolUser cmdlet without using the All parameter, only the first 500 user accounts are
returned.

Specific Office 365 services for specific users for a single licensing plan
To disable a specific set of Office 365 services for users from a single licensing plan, perform the following steps:
1. Identify the undesirable services in the licensing plan by using the following syntax:

$LO = New-MsolLicenseOptions -AccountSkuId <AccountSkuId> -DisabledPlans "<UndesirableService1>", "


<UndesirableService2>"...

The following example creates a LicenseOptions object that disables the Office Online and SharePoint
Online services in the licensing plan named litwareinc:ENTERPRISEPACK (Office 365 Enterprise E3).

$LO = New-MsolLicenseOptions -AccountSkuId "litwareinc:ENTERPRISEPACK" -DisabledPlans "SHAREPOINTWAC",


"SHAREPOINTENTERPRISE"

2. Use the LicenseOptions object from Step 1 on one or more users.


To create a new account that has the services disabled, use the following syntax:

New-MsolUser -UserPrincipalName <Account> -DisplayName <DisplayName> -FirstName <FirstName> -LastName


<LastName> -LicenseAssignment <AccountSkuId> -LicenseOptions $LO -UsageLocation <CountryCode>

The following example creates a new account for Allie Bellew that assigns the license and disables the
services described in Step 1.

New-MsolUser -UserPrincipalName [email protected] -DisplayName "Allie Bellew" -FirstName Allie -


LastName Bellew -LicenseAssignment litwareinc:ENTERPRISEPACK -LicenseOptions $LO -UsageLocation US

For more information about creating user accounts in Office 365 PowerShell, see Create user accounts
with Office 365 PowerShell.
To disable the services for an existing licensed user, use the following syntax:

Set-MsolUserLicense -UserPrincipalName <Account> -LicenseOptions $LO

This example disables the services for the user [email protected].

Set-MsolUserLicense -UserPrincipalName [email protected] -LicenseOptions $LO

To disable the services described in Step 1 for all existing licensed users, specify the name of your Office
365 plan from the display of the Get-MsolAccountSku cmdlet (such as
litwareinc:ENTERPRISEPACK), and then run the following commands:

$acctSKU="<AccountSkuId>"
$AllLicensed = Get-MsolUser -All | Where {$_.isLicensed -eq $true -and
$_.licenses[0].AccountSku.SkuPartNumber -eq ($acctSKU).Substring($acctSKU.IndexOf(":")+1,
$acctSKU.Length-$acctSKU.IndexOf(":")-1)}
$AllLicensed | ForEach {Set-MsolUserLicense -UserPrincipalName $_.UserPrincipalName -LicenseOptions
$LO}

To disable the services for a group of existing users, use either of the following methods to identify
the users:
Filter the accounts based on an existing account attribute To do this, use the following syntax:

$x = Get-MsolUser -All <FilterableAttributes>


$x | ForEach {Set-MsolUserLicense -UserPrincipalName $_.UserPrincipalName -LicenseOptions $LO}

The following example disables the services for users in the Sales department in the United States.

$USSales = Get-MsolUser -All -Department "Sales" -UsageLocation "US"


$USSales | ForEach {Set-MsolUserLicense -UserPrincipalName $_.UserPrincipalName -LicenseOptions $LO}

Use a list of specific accounts To do this, perform the following steps:


3. Create a text file that contains one account on each line like this:

[email protected]
[email protected]
[email protected]
In this example, the text file is C:\My Documents\Accounts.txt.
4. Run the following command:

Get-Content "C:\My Documents\Accounts.txt" | foreach {Set-MsolUserLicense -UserPrincipalName $_ -


LicenseOptions $LO}

To disable Office 365 services for users while you are assigning them to a licensing plan, see Disable access to
services while assigning user licenses.

Specific Office 365 services for users from all licensing plans
To disable Office 365 services for users in all available licensing plans, perform the following steps:
1. Copy and paste this script into Notepad.

$AllLicensingPlans = Get-MsolAccountSku
for($i = 0; $i -lt $AllLicensingPlans.Count; $i++)
{
$O365Licences = New-MsolLicenseOptions -AccountSkuId $AllLicensingPlans[$i].AccountSkuId -
DisabledPlans "<UndesirableService1>", "<UndesirableService2>"...
Set-MsolUserLicense -UserPrincipalName <Account> -LicenseOptions $O365Licences
}

2. Customize the following values for your environment:


In this example, we'll use Office Online and SharePoint Online.
In this example, we'll use [email protected].
The customized script looks like this:

$AllLicensingPlans = Get-MsolAccountSku
for($i = 0; $i -lt $AllLicensingPlans.Count; $i++)
{
$O365Licences = New-MsolLicenseOptions -AccountSkuId $AllLicensingPlans[$i].AccountSkuId -
DisabledPlans "SHAREPOINTWAC", "SHAREPOINTENTERPRISE"
Set-MsolUserLicense -UserPrincipalName [email protected] -LicenseOptions $O365Licences
}

3. Save the script as RemoveO365Services.ps1 in a location that's easy for you to find. For this example, we'll
save the file in C:\\O365 Scripts .
4. Run the script in Office 365 PowerShell by using the following command.

& "C:\O365 Scripts\RemoveO365Services.ps1"

NOTE
To reverse the effects of any of these procedures (that is, to re-enable the disabled services), run the procedure again, but
use the value $null for the DisabledPlans parameter.

Return to top

All Office 365 services for all users for a single licensing plan
To disable all Office 365 services for all users in a specific licensing plan, specify the licensing plan name for
$acctSKU (such as litwareinc:ENTERPRISEPACK), and then run these commands in the PowerShell command
window:

$acctSKU="<AccountSkuId>"
$servicesList=(Get-MsolAccountSku | Select -ExpandProperty ServiceStatus).ServicePlan.ServiceName
$lo = New-MsolLicenseOptions -AccountSkuId $acctSKU -DisabledPlans $servicesList
$AllLicensed = Get-MsolUser -All | Where {$_.isLicensed -eq $true -and $_.licenses[0].AccountSku.SkuPartNumber
-eq ($acctSKU).Substring($acctSKU.IndexOf(":")+1, $acctSKU.Length-$acctSKU.IndexOf(":")-1)}
$AllLicensed | ForEach {Set-MsolUserLicense -ObjectID $_.ObjectID -LicenseOptions $lo}

New to Office 365?


TIP
New to Office 365?
Discover free video courses for Office 365 admins and IT pros, brought to you by LinkedIn Learning.

See also
See the following additional topics about managing users with Office 365 PowerShell:
Delete and restore user accounts with Office 365 PowerShell
Delete and restore user accounts with Office 365 PowerShell
Block user accounts with Office 365 PowerShell
Assign licenses to user accounts with Office 365 PowerShell
Create user accounts with Office 365 PowerShell
For more information about the cmdlets that are used in these procedures, see the following topics:
Get-Content
Get-MsolAccountSku
New -MsolLicenseOptions
Get-MsolUser
New -MsolUser
Set-MsolUserLicense
ForEach-Object
Where-Object
Disable access to Sway with Office 365 PowerShell
2/13/2018 • 1 min to read • Edit Online

Summary Use the ManageSway.ps1 PowerShell script to disable access to Sway in your Office 365 organization.
The ManageSway.ps1 PowerShell script allows you to view and disable services in your Office 365 organization,
including Sway. This script automates the procedures that are described in the following topics:
View licenses and services with Office 365 PowerShell
Disable access to services with Office 365 PowerShell
You need to download the two files that are associated with the script:
The ManageSway.ps1 script at https://go.microsoft.com/fwlink/p/?LinkId=785070
The help file for the script at https://go.microsoft.com/fwlink/p/?LinkId=785072
Disable access to services while assigning user
licenses
5/8/2018 • 3 min to read • Edit Online

Summary: Learn how to assign licenses to user accounts and disable specific service plans at the same time using
Office 365 PowerShell.
Office 365 subscriptions come with service plans for individual services. Office 365 administrators often need to
disable certain plans when assigning licenses to users. With the instructions in this article, you can assign an Office
365 license while disabling specific service plans using PowerShell for an individual user account or multiple user
accounts.

Before you begin


The procedures in this topic require you to connect to Office 365 PowerShell. For instructions, see Connect to
Office 365 PowerShell.

Collect information about subscriptions and service plans


Run this command to see your current subscriptions:

Get-MsolAccountSku

In the display of the Get-MsolAccountSku command:


AccountSkuId is a subscription for your organization in <OrganizationName>:<Subscription> format. The
<OrganizationName> is the value that you provided when you enrolled in Office 365, and is unique for
your organization. The <Subscription> value is for a specific subscription. For example, for
litwareinc:ENTERPRISEPACK, the organization name is litwareinc, and the subscription name is
ENTERPRISEPACK (Office 365 Enterprise E3).
ActiveUnits is the number of licenses that you've purchased for the subscription.
WarningUnits is the number of licenses in a subscription that you haven't renewed, and that will expire
after the 30-day grace period.
ConsumedUnits is the number of licenses that you've assigned to users for the subscription.
Note the AccountSkuId for your Office 365 subscription that contains the users you want to license. Also, ensure
that there are enough licenses to assign (subtract ConsumedUnits from ActiveUnits ).
Next, run this command to see the details about the Office 365 service plans that are available in all your
subscriptions:

Get-MsolAccountSku | Select -ExpandProperty ServiceStatus

From the display of this command, determine which service plans you would like to disable when you assign
licenses to users.
Here is a partial list of service plans and their corresponding Office 365 services.
SERVICE PLAN DESCRIPTION

SWAY Sway

INTUNE_O365 Mobile Device Management for Office 365

YAMMER_ENTERPRISE Yammer

RMS_S_ENTERPRISE Azure Rights Management (RMS)

OFFICESUBSCRIPTION Office Professional Plus

MCOSTANDARD Skype for Business Online

SHAREPOINTWAC Office Online

SHAREPOINTENTERPRISE SharePoint Online

EXCHANGE_S_ENTERPRISE Exchange Online Plan 2

Now that you have the AccountSkuId and the service plans to disable, you can assign licenses for an individual
user or for multiple users.

For a single user


For a single user, fill in the user principal name of the user account, the AccountSkuId, and the list of service plans
to disable and remove the explanatory text and the < and > characters. Then, run the resulting commands at the
PowerShell command prompt.

$userUPN="<the user's account name in email format>"


$accountSkuId="<the AccountSkuId from the Get-MsolAccountSku command>"
$planList=@( <comma-separated, double-quote enclosed list of the service plans to disable> )
$licenseOptions=New-MsolLicenseOptions -AccountSkuId $accountSkuId -DisabledPlans $planList
$user=Get-MsolUser -UserPrincipalName $userUPN
$usageLocation=$user.Usagelocation
Set-MsolUserLicense -UserPrincipalName $userUpn -AddLicenses $accountSkuId -ErrorAction SilentlyContinue
Sleep -Seconds 5
Set-MsolUserLicense -UserPrincipalName $userUpn -LicenseOptions $licenseOptions -ErrorAction SilentlyContinue
Set-MsolUser -UserPrincipalName $userUpn -UsageLocation $usageLocation

Here is an example command block for the account named [email protected], for the
contoso:ENTERPRISEPACK license, and the service plans to disable are RMS_S_ENTERPRISE, SWAY,
INTUNE_O365, and YAMMER_ENTERPRISE:

$userUPN="[email protected]"
$accountSkuId="contoso:ENTERPRISEPACK"
$planList=@( "RMS_S_ENTERPRISE","SWAY","INTUNE_O365","YAMMER_ENTERPRISE" )
$licenseOptions=New-MsolLicenseOptions -AccountSkuId $accountSkuId -DisabledPlans $planList
$user=Get-MsolUser -UserPrincipalName $userUPN
$usageLocation=$user.Usagelocation
Set-MsolUserLicense -UserPrincipalName $userUpn -AddLicenses $accountSkuId -ErrorAction SilentlyContinue
Sleep -Seconds 5
Set-MsolUserLicense -UserPrincipalName $userUpn -LicenseOptions $licenseOptions -ErrorAction SilentlyContinue
Set-MsolUser -UserPrincipalName $userUpn -UsageLocation $UsageLocation
For multiple users
To perform this administration task for multiple users, create a comma-separated value (CSV ) text file that contains
the UserPrincipalName and UsageLocation fields. Here is an example:

UserPrincipalName,UsageLocation
[email protected],FR
[email protected],US
[email protected],US

Next, fill in the location of the input and output CSV files, the account SKU ID, and the list of service plans to
disable, and then run the resulting commands at the PowerShell command prompt.

$inFileName="<path and file name of the input CSV file that contains the users, example:
C:\admin\Users2License.CSV>"
$outFileName="<path and file name of the output CSV file that records the results, example:
C:\admin\Users2License-Done.CSV>"
$accountSkuId="<the AccountSkuId from the Get-MsolAccountSku command>"
$planList=@( <comma-separated, double-quote enclosed list of the plans to disable> )
$users=Import-Csv $inFileName
$licenseOptions=New-MsolLicenseOptions -AccountSkuId $accountSkuId -DisabledPlans $planList
ForEach ($user in $users)
{
$user.Userprincipalname
$upn=$user.UserPrincipalName
$usageLocation=$user.UsageLocation
Set-MsolUserLicense -UserPrincipalName $upn -AddLicenses $AccountSkuId -ErrorAction SilentlyContinue
sleep -Seconds 5
Set-MsolUserLicense -UserPrincipalName $upn -LicenseOptions $licenseOptions -ErrorAction SilentlyContinue
Set-MsolUser -UserPrincipalName $upn -UsageLocation $usageLocation
$users | Get-MsolUser | Select UserPrincipalName, Islicensed,Usagelocation | Export-Csv $outFileName
}

This PowerShell command block:


Displays the user principal name of each user.
Assigns customized licenses to each user.
Creates a CSV file with all the users that were processed and shows their license status.

See also
Disable access to services with Office 365 PowerShell
Disable access to Sway with Office 365 PowerShell
Manage user accounts and licenses with Office 365 PowerShell
Manage Office 365 with Office 365 PowerShell
Remove licenses from user accounts with Office 365
PowerShell
2/13/2018 • 4 min to read • Edit Online

Summary: Explains how to use Office 365 PowerShell to remove Office 365 licenses that were previously
assigned to users.

Before you begin


The procedures in this topic require you to connect to Office 365 PowerShell. For instructions, see Connect
to Office 365 PowerShell.
To view the licensing plan ( AccountSkuID ) information in your organization, see the following topics:
View licenses and services with Office 365 PowerShell
View account license and service details with Office 365 PowerShell
If you use the Get-MsolUser cmdlet without using the -All parameter, only the first 500 accounts are
returned.

The short version (instructions without explanations)


This section presents the procedures without fanfare or superfluous explanation. If you have questions or want
more information, you can read rest of the topic.
To remove licenses from an existing user account, use the following syntax:

Set-MsolUserLicense -UserPrincipalName <Account> -RemoveLicenses "<AccountSkuId1>", "<AccountSkuId2>"...

This example removes the litwareinc:ENTERPRISEPACK (Office 365 Enterprise E3) license from the user account
[email protected].

Set-MsolUserLicense -UserPrincipalName [email protected] -RemoveLicenses "litwareinc:ENTERPRISEPACK"

To remove licenses from a group of existing licensed users, use either of the following methods:
Filter the accounts based on an existing account attribute To do this, use the following syntax:

$x = Get-MsolUser -All <FilterableAttributes> | where {$_.isLicensed -eq $true}


$x | foreach {Set-MsolUserLicense -UserPrincipalName $_.UserPrincipalName -RemoveLicenses "<AccountSkuId1>", "
<AccountSkuId2>"...}

This example removes the litwareinc:ENTERPRISEPACK (Office 365 Enterprise E3) licenses from all accounts for
users in the Sales department in the United States.

$USSales = Get-MsolUser -All -Department "Sales" -UsageLocation "US" | where {$_.isLicensed -eq $true}
$USSales | foreach {Set-MsolUserLicense -UserPrincipalName $_.UserPrincipalName -RemoveLicenses
"litwareinc:ENTERPRISEPACK"}
Use a list of specific accounts To do this, perform the following steps:
1. Create and save a text file that contains one account on each line like this:

[email protected]
[email protected]
[email protected]

2. Use the following syntax:

Get-Content "<FileNameAndPath>" | Set-MsolUserLicense -UserPrincipalName $_.UserPrincipalName -


RemoveLicenses "<AccountSkuId1>", "<AccountSkuId2>"...

This example removes the litwareinc:ENTERPRISEPACK (Office 365 Enterprise E3) license from the user accounts
defined in the text file C:\My Documents\Accounts.txt.

Get-Content "C:\My Documents\Accounts.txt" | Set-MsolUserLicense -UserPrincipalName $_.UserPrincipalName -


RemoveLicenses "litwareinc:ENTERPRISEPACK"

To remove licenses from all existing user accounts, use the following syntax:

$x = Get-MsolUser -All | where {$_.isLicensed -eq $true}


$x | foreach {Set-MsolUserLicense -UserPrincipalName $_.UserPrincipalName -RemoveLicenses "<AccountSkuId1>", "
<AccountSkuId2>"...}

This example removes the litwareinc:ENTERPRISEPACK (Office 365 Enterprise E3) license from all existing licensed
user accounts.

$x = Get-MsolUser -All | where {$_.isLicensed -eq $true}


$x | foreach {Set-MsolUserLicense -UserPrincipalName $_.UserPrincipalName -RemoveLicenses
"litwareinc:ENTERPRISEPACK"}

The long version (instructions with detailed explanations)


Nothing lasts forever, and that includes Office 365 licenses: sooner or later, there will come a time when you need
to remove a license from a user account. Maybe the user is going on leave; maybe the user no longer needs the
license; maybe - well, there are obviously any number of reasons why you might want to remove a user license.
Before we go any further it's important to note that removing a license requires you to, well, remove the license:
disabling all the services on a license is not the same thing as removing a license. For example, suppose we've
used up all our Office 365 licenses; in other words, we have no licenses available whatsoever. You decide to follow
the procedure in Disable access to services with Office 365 PowerShell to disable all the services, say, on Belinda
Newman's account. After we do that, how many licenses will we have available to us? That's right: zero. Yes, the
procedure from that topic will disable all the services on Belinda's license, but it will not disable (i.e., delete) the
license itself. The license will still be valid, and it will still be assigned to Belinda Newman. She just won't be able to
use that license to access any Office 365 services.
And that's important: if you want to remove a license from a user you must actually remove the license. Disabling
all the services will prevent the user from logging on to Office 365, but it won't free up his or her license. If you
want to take back a license that's currently assigned to a user you need to run a command similar to this one, a
command that uses the RemoveLicenses parameter to actually remove the license previously assigned to Belinda:
Set-MsolUserLicense -UserPrincipalName [email protected] -RemoveLicenses "litwareinc:ENTERPRISEPACK"

Run that command, and Belinda Newman will no longer be licensed to use Office 365.

NOTE
As you can see, when you use the RemoveLicenses parameter you need to specify the name of the license to be removed. If
you aren't sure which licensing plan was used to assign a license to the user just run a command like this:
Get-MsolUser -UserPrincipalName [email protected] | Format-List DisplayName,Licenses

To verify that the license really was removed, use the Get-MsolUser to check the user account in question:

Get-MsolUser -UserPrincipalName [email protected]

If everything went according to plan, Belinda's isLicensed property will now be set to False :

UserPrincipalName DisplayName isLicensed


----------------- ----------- ----------
[email protected] Newman, Belinda False

Another way to free up a license is by deleting the user account. For more information, see Delete and restore
user accounts with Office 365 PowerShell.

See also
See the following additional topics about managing users with Office 365 PowerShell:
Create user accounts with Office 365 PowerShell
Delete and restore user accounts with Office 365 PowerShell
Block user accounts with Office 365 PowerShell
Assign licenses to user accounts with Office 365 PowerShell
For more information about the cmdlets that are used in these procedures, see the following topics:
Get-Content
Get-MsolUser
Set-MsolUserLicense
ForEach-Object
Where-Object

New to Office 365?


TIP
New to Office 365?
Discover free video courses for Office 365 admins and IT pros, brought to you by LinkedIn Learning.
Block user accounts with Office 365 PowerShell
2/13/2018 • 3 min to read • Edit Online

Summary: Explains how to use Office 365 PowerShell to block and unblock access to Office 365 accounts.
Blocking access to an Office 365 account prevents anyone from using the account to sign in and access the
services and data in your Office 365 organization. When you block access to the account, the user receives the
following error message when they attempt to sign in:

You can use Office 365 PowerShell to block access to individual and multiple user accounts.

Before you begin


The procedures in this topic require you to connect to Office 365 PowerShell. For instructions, see Connect
to Office 365 PowerShell.
When you block a user account, it might take as long as 24 hours to take effect on all the user's devices
and clients.

Use Office 365 PowerShell to block access to individual user accounts


Use the following syntax to block access to an individual user account:

Set-MsolUser -UserPrincipalName <UPN of user account> -BlockCredential $true

This example blocks access to the user account [email protected].

Set-MsolUser -UserPrincipalName [email protected] -BlockCredential $true

To unblock the user account, run the following command:

Set-MsolUser -UserPrincipalName <UPN of user account> -BlockCredential $false

At any time, you can check the blocked status of a user account with the following command:

Get-MolUser -UserPrincipalName <UPN of user account> | Select DisplayName,BlockCredential


Use Office 365 PowerShell to block access to multiple user accounts
First, create a text file that contains one account on each line like this:

[email protected]
[email protected]
[email protected]

In the following commands, the example text file is C:\My Documents\Accounts.txt. Replace this with the path and
file name of your text file.
To block access to the accounts listed in the text file, run the following command:

Get-Content Accounts.txt | ForEach { Set-MsolUser -UserPrincipalName $_ -BlockCredential $true }

To unblock the accounts listed in the text file, run the following command:

Get-Content Accounts.txt | ForEach { Set-MsolUser -UserPrincipalName $_ -BlockCredential $false }

Use the Azure Active Directory V2 PowerShell module to block access


to user accounts
To use the New-AzureADUser cmdlet from the Azure Active Directory V2 PowerShell module, you must first
connect to your subscription. For the instructions, seeConnect with the Azure Active Directory V2 PowerShell
module.
After you have connected, use the following syntax to block an individual user account:

Set-AzureADUser -ObjectID <UPN of user account> -AccountEnabled $false

NOTE
The -ObjectID parameter in the Set-AzureAD cmdlet accepts either the account name, also known as the User Principal
Name, or the account's object ID.

This example blocks access to the user account [email protected].

Set-AzureADUser -ObjectID [email protected] -AccountEnabled $false

To unblock this user account, run the following command:

Set-AzureADUser -ObjectID [email protected] -AccountEnabled $true

To display the user account UPN based on the user's display name, use the following commands:

$userName="<user account display name>"


Write-Host (Get-AzureADUser | where {$_.DisplayName -eq $userName}).UserPrincipalName

This example displays the user account UPN for the user named Caleb Sills.
$userName="Caleb Sills"
Write-Host (Get-AzureADUser | where {$_.DisplayName -eq $userName}).UserPrincipalName

To block an account based on the user's name, use the following commands:

$userName="<user account display name>"


Set-AzureADUser -ObjectID (Get-AzureADUser | where {$_.DisplayName -eq $userName}).UserPrincipalName -
AccountEnabled $false

At any time, you can check the blocked status of a user account with the following command:

Get-AzureADUser -UserPrincipalName <UPN of user account> | Select DisplayName,AccountEnabled

To block access to multiple user accounts, create a text file that contains one account name on each line like this:

[email protected]
[email protected]
[email protected]

In the following commands, the example text file is C:\My Documents\Accounts.txt. Replace this with the path and
file name of your text file.
To block access to the accounts listed in the text file, run the following command:

Get-Content "C:\My Documents\Accounts.txt" | ForEach { Set-AzureADUSer -ObjectID $_ -AccountEnabled $false }

To unblock the accounts listed in the text file, run the following command:

Get-Content "C:\My Documents\Accounts.txt" | ForEach { Set-AzureADUSer -ObjectID $_ -AccountEnabled $true }

See also
See the following additional topics about managing users with Office 365 PowerShell:
Create user accounts with Office 365 PowerShell
Delete and restore user accounts with Office 365 PowerShell
Assign licenses to user accounts with Office 365 PowerShell
Remove licenses from user accounts with Office 365 PowerShell
For more information about the cmdlets that are used in these procedures, see the following topics:
Get-Content
Set-MsolUser
New -AzureADUser
Delete and restore user accounts with Office 365
PowerShell
2/13/2018 • 2 min to read • Edit Online

Summary: Learn how to use Office 365 PowerShell to delete and restore Office 365 user accounts.
When you use Office 365 PowerShell to delete a user account, the account isn't permanently deleted. You can
restore the deleted user account within 30 days.

Before you begin


The procedures in this topic require you to connect to Office 365 PowerShell. For instructions, see
Connect to Office 365 PowerShell.
If you use the Get-MsolUser cmdlet without using the -All parameter, only the first 500 accounts are
returned.

Use Office 365 PowerShell to block access to individual user accounts


To delete a user account, use the following syntax:

Remove-MsolUser -UserPrincipalName <Account>

This example deletes the user account [email protected].

Remove-MsolUser -UserPrincipalName [email protected]

To restore a deleted user account within the 30-day grace period, use the following syntax:

Restore-MsolUser -UserPrincipalName <Account>

This example restores the deleted account [email protected].

Restore-MsolUser -UserPrincipalName [email protected]

Notes:
To see the list of deleted users that can be restored, run the following command:

Get-MsolUser -All -ReturnDeletedUsers

If the user account's original user principal name is used by another account, use the
NewUserPrincipalName parameter instead of UserPrincipalName to specify a different user principal
name when you restore the user account.

Use the Azure Active Directory V2 PowerShell module to remove a


user account
To use the Remove-AzureADUser cmdlet from the Azure Active Directory V2 PowerShell module, you must
first connect to your subscription. For the instructions, see Connect with the Azure Active Directory V2
PowerShell module.
After you have connected, use the following syntax to remove an individual user account:

Remove-AzureADUser -ObjectID <Account>

This example removes the user account [email protected].

Remove-AzureADUser -ObjectID [email protected]

NOTE
The -ObjectID parameter in the Remove-AzureAD cmdlet accepts either the account name, also known as the User
Principal Name, or the account's object ID.

To display the account name based on the user's name, use the following commands:

$userName="<User name>"
Write-Host (Get-AzureADUser | where {$_.DisplayName -eq $userName}).UserPrincipalName

This example displays the account name for the user named Caleb Sills.

$userName="Caleb Sills"
Write-Host (Get-AzureADUser | where {$_.DisplayName -eq $userName}).UserPrincipalName

To remove an account based on the user's name, use the following commands:

$userName="<User name>"
Remove-AzureADUser -ObjectID (Get-AzureADUser | where {$_.DisplayName -eq $userName}).UserPrincipalName

See also
See these additional topics about managing users with Office 365 PowerShell:
Create user accounts with Office 365 PowerShell
Block user accounts with Office 365 PowerShell
Assign licenses to user accounts with Office 365 PowerShell
Remove licenses from user accounts with Office 365 PowerShell
For more information about the cmdlets that are used in these procedures, see the following topics:
Get-MsolUser
Remove-MsolUser
Restore-MsolUser
New -AzureADUser
Create user accounts with Office 365 PowerShell
2/13/2018 • 4 min to read • Edit Online

Summary: Learn how to use Office 365 PowerShell to create user accounts in Office 365.
You can use Office 365 PowerShell to efficiently create user accounts, especially multiple user accounts. When
you create user accounts in Office 365 PowerShell, certain account properties are always required. Other
properties aren't required to create the account, but are otherwise important. These properties are described in
the following table:

PROPERTY NAME REQUIRED? DESCRIPTION

DisplayName Yes This is the display name that's used in


Office 365 services. For example, Caleb
Sills.

UserPrincipalName Yes This is the account name that's used to


sign in to Office 365 services. For
example,
[email protected].

FirstName No

LastName No

LicenseAssignment No This is the licensing plan (also known as


the license plan, Office 365 plan, or
SKU) from which an available license is
assigned to the user account. The
license defines the Office 365 services
that are available to account. You don't
have to assign a license to a user when
you create the account, but the
account requires a license to access
Office 365 services. You have 30 days
to license the user account after you
create it.
Use the Get-MsolAccountSku cmdlet
to view the licensing plans (
AccountSkuId ) and available licenses
in your organization. For more
information, see View licenses and
services with Office 365 PowerShell.
PROPERTY NAME REQUIRED? DESCRIPTION

Password No If you don't specify a password, a


random password is assigned to the
user account, and the password is
visible in the results of the command. If
you specify a password, it needs to
meet the following complexity
requirements:
8 to 16 ASCII text characters.
Characters from any three of the
following types: lowercase letters,
uppercase letters, numbers, and
symbols.

UsageLocation No This is a valid ISO 3166-1 alpha-2


country code. For example, US for the
United States, and FR for France. It's
important to provide this value,
because some Office 365 services
aren't available in certain countries, so
you can't assign a license to a user
account unless the account has this
value configured. For more
information, see About license
restrictions.

Before you begin


The procedures in this topic require you to connect to Office 365 PowerShell. For instructions, see Connect to
Office 365 PowerShell.

Use Office 365 PowerShell to create individual user accounts


To create an individual account, use the following syntax:

New-MsolUser -DisplayName <DisplayName> -FirstName <FirstName> -LastName <LastName> -UserPrincipalName


<Account> -UsageLocation <CountryCode> -LicenseAssignment <AccountSkuID> [-Password <Password>]

This example creates an account for the United States user named Caleb Sills, and assigns a license from the
contoso:ENTERPRISEPACK ( Office 365 Enterprise E3 ) licensing plan.

New-MsolUser -DisplayName "Caleb Sills" -FirstName Caleb -LastName Sills -UserPrincipalName


[email protected] -UsageLocation US -LicenseAssignment contoso:ENTERPRISEPACK

Use Office 365 PowerShell to create multiple user accounts


1. Create a comma-separated value (CSV ) file that contains the required user account information. For
example:

UserPrincipalName,FirstName,LastName,DisplayName,UsageLocation,AccountSkuId
[email protected],Claude,Loiselle,Claude Loiselle,US,contoso:ENTERPRISEPACK
[email protected],Lynne,Baxter,Lynne Baxter,US,contoso:ENTERPRISEPACK
[email protected],Shawn,Melendez,Shawn Melendez,US,contoso:ENTERPRISEPACK
NOTE
The column names and their order in the first row of the CSV file are arbitrary, but make sure the data in the rest of
the file matches the order of the column names, and use the column names for the parameter values in the Office
365 PowerShell command.

2. Use the following syntax:

Import-Csv -Path <Input CSV File Path and Name> | foreach {New-MsolUser -DisplayName $_.DisplayName -
FirstName $_.FirstName -LastName $_.LastName -UserPrincipalName $_.UserPrincipalName -UsageLocation
$_.UsageLocation -LicenseAssignment $_.AccountSkuId [-Password $_.Password]} | Export-Csv -Path
<Output CSV File Path and Name>

This example creates the user accounts from the file named C:\My Documents\NewAccounts.csv, and logs the
results in the file named C:\My Documents\NewAccountResults.csv

Import-Csv -Path "C:\My Documents\NewAccounts.csv" | foreach {New-MsolUser -DisplayName $_.DisplayName -


FirstName $_.FirstName -LastName $_.LastName -UserPrincipalName $_.UserPrincipalName -UsageLocation
$_.UsageLocation -LicenseAssignment $_.AccountSkuId} | Export-Csv -Path "C:\My
Documents\NewAccountResults.csv"

1. Review the output file to see the results. We didn't specify passwords, so the random passwords that were
generated are visible in the output file.

Use the Azure Active Directory V2 PowerShell module to create


individual user accounts
To use the New-AzureADUser cmdlet from the Azure Active Directory V2 PowerShell module, you must first
connect to your subscription. For the instructions, see Connect with the Azure Active Directory V2 PowerShell
module.
After you have connected, use the following syntax to create an individual account:

$PasswordProfile=New-Object -TypeName Microsoft.Open.AzureAD.Model.PasswordProfile


$PasswordProfile.Password="<user account password>"
New-AzureADUser -DisplayName <DisplayName> -GivenName <FirstName> -SurName <LastName> -UserPrincipalName
<Account> -UsageLocation <CountryCode> -MailNickName <mailbox name> -PasswordProfile $PasswordProfile -
AccountEnabled $true

This example creates an account for the United States user named Caleb Sills:

$PasswordProfile=New-Object -TypeName Microsoft.Open.AzureAD.Model.PasswordProfile


$PasswordProfile.Password="3Rv0y1q39/chsy"
New-AzureADUser -DisplayName "Caleb Sills" -GivenName "Caleb" -SurName "Sills" -UserPrincipalName
[email protected] -UsageLocation US -MailNickName calebs -PasswordProfile $PasswordProfile -
AccountEnabled $true

See also
See these additional topics about managing users with Office 365 PowerShell:
Delete and restore user accounts with Office 365 PowerShell
Block user accounts with Office 365 PowerShell
Assign licenses to user accounts with Office 365 PowerShell
Remove licenses from user accounts with Office 365 PowerShell
For more information about the cmdlets that are used in these procedures, see the following topics:
Export-Csv
Import-Csv
New -MsolUser
ForEach-Object
New -AzureADUser
View user accounts with Office 365 PowerShell
2/13/2018 • 8 min to read • Edit Online

Summary: View, list, or display your user accounts in various ways with Office 365 PowerShell.
Although you can use the Office 365 Admin center to view the accounts for your Office 365 tenant, you can also
use Office 365 PowerShell and do some things that the Office 365 Admin center cannot.

Before you begin


The procedures in this topic require you to connect to Office 365 PowerShell. For instructions, see Connect to
Office 365 PowerShell.

Display Office 365 user account information


To display the full list of user accounts, run this command in your Office 365 PowerShell command prompt or the
PowerShell Integrated Script Environment (ISE ).

Get-MsolUser

You should see information similar to this:

UserPrincipalName DisplayName isLicensed


----------------- ----------- ----------
[email protected] Zrinka Makovac True
[email protected] Bonnie Kearney True
[email protected] Fabrice Canel True
[email protected] Brian Johnson False
AnneWlitwareinc.onmicrosoft.com Anne Wallace True
[email protected] Scott Wallace False

The Get-MsolUser cmdlet also has a set of parameters to filter the set of user accounts displayed. For example,
for the list of unlicensed users (users who've been added to Office 365 but haven't yet been licensed to use any of
the services), run this command.

Get-MsolUser -UnlicensedUsersOnly

You should see information similar to this:

UserPrincipalName DisplayName isLicensed


----------------- ----------- ----------
[email protected] Brian Johnson False
[email protected] Scott Wallace False

For more information about additional parameters to filter the display the set of user accounts displayed, see Get-
MsolUser .
To be more selective about the list of accounts to display, you can use the Where-Object cmdlet in combination
with the Get-MsolUser cmdlet. To combine the two cmdlets, we use the "pipe" character "|", which tells Office 365
PowerShell to take the results of one command and send it to the next command. Here is an example command
that displays only those user accounts that have an unspecified usage location:

Get-MsolUser | Where-Object {$_.UsageLocation -eq $Null}

This command instructs Office 365 PowerShell to:


Get all of the information on the user accounts ( Get-MsolUser ) and send it to the next command ( | ).
Find all of the user accounts that have an unspecified usage location ( Where-Object {$_.UsageLocation -
eq $Null} ). Inside the braces, the command instructs Office 365 PowerShell to only find the set of
accounts in which the UsageLocation user account property ( $_.UsageLocation ) is not specified ( -eq
$Null ).
You should see information similar to this:

UserPrincipalName DisplayName isLicensed


----------------- ----------- ----------
[email protected] Brian Johnson False
[email protected] Scott Wallace False

The UsageLocation property is only one of many properties associated with a user account. To see all of the
properties for user accounts, use the Select-Object cmdlet and the wildcard character (*) to display them all for a
specific user account. Here is an example:

Get-MsolUser -UserPrincipalName "[email protected]" | Select-Object *

For example, from this list, City is the name of a user account property. This means you can use the following
command to list all of the user accounts for users living in London:

Get-MsolUser | Where-Object {$_.City -eq "London"}

TIP
The syntax for the Where-Object cmdlet shown in these examples is Where-Object {$_. [user account property name]
[comparison operator] [value] }.> [comparison operator] is -eq for equals, -ne for not equals, -lt for less than, -gt for greater
than, and others> [value] is typically a string (a sequence of letters, numbers, and other characters), a numerical value, or
$Null for unspecified> See Where-Object for more information.

You can check the blocked status of a user account with the following command:

Get-MolUser -UserPrincipalName <UPN of user account> | Select DisplayName,BlockCredential

Select the user account properties to display


The Get-MsolUser cmdlet by default displays three properties of user accounts:
UserPrincipalName
DisplayName
isLicensed
If you need additional properties, such as the department the user works for and the country/region where the
user uses Office 365 services, you can run Get-MsolUser in combination with the Select-Object cmdlet to
specify the list of user account properties. Here is an example:

Get-MsolUser | Select-Object DisplayName, Department, UsageLocation

This command instructs Office 365 PowerShell to:


Get all of the information on the user accounts ( Get-MsolUser ) and send it to the next command ( | ).
Display only the user account name, department, and usage location ( Select-Object DisplayName,
Department, UsageLocation ).
You should see information similar to this:

DisplayName Department UsageLocation


----------- ---------- -------------
Zrinka Makovac Sales & Marketing US
Bonnie Kearney Sales & Marketing US
Fabrice Canel Legal US
Brian Johnson
Anne Wallace Executive Management US
Alex Darrow Sales & Marketing US
David Longmuir Operations US
Scott Wallace Operations

The Select-Object cmdlet allows you to pick and choose the properties you want a command to display. To see all
of the properties for user accounts, use the wildcard character (*) to display them all for a specific user account.
Here is an example:

Get-MsolUser -UserPrincipalName "[email protected]" | Select-Object *

To be more selective about the list of accounts to display, you can also use the Where-Object cmdlet. Here is an
example command that displays only those user accounts that have an unspecified usage location:

Get-MsolUser | Where-Object {$_.UsageLocation -eq $Null} | Select-Object DisplayName, Department,


UsageLocation

This command instructs Office 365 PowerShell to:


Get all of the information on the user accounts ( Get-MsolUser ) and send it to the next command ( | ).
Find all of the user accounts that have an unspecified usage location ( Where-Object {$_.UsageLocation -
eq $Null} ) and send the resulting information to the next command ( | ). Inside the braces, the command is
instructing Office 365 PowerShell to only find the set of accounts in which the UsageLocation user account
property ( $_.UsageLocation ) is not specified ( -eq $Null ).
Display only the user account name, department, and usage location ( Select-Object DisplayName,
Department, UsageLocation ).
You should see information similar to this:

DisplayName Department UsageLocation


----------- ---------- -------------
Brian Johnson
Scott Wallace Operations
Use the Azure Active Directory V2 PowerShell module to display user
accounts
To display properties for user accounts with the Azure Active Directory V2 PowerShell module, you use the Get-
AzureADUser cmdlet. But first, you must connect to your subscription. For the instructions, seeConnect with the
Azure Active Directory V2 PowerShell module.
Display Office 365 user account information
To display the full list of user accounts, run this command in your Office 365 PowerShell command prompt or the
PowerShell Integrated Script Environment (ISE ).

Get-AzureADUser

The Get-AzureADUser cmdlet by default displays three properties of user accounts:


ObjectID
DisplayName
UserPrincipalName
To be more selective about the list of accounts to display, you can use the Where-Object cmdlet in combination
with the Get-AzureADUser cmdlet. To combine the two cmdlets, we use the "pipe" character "|", which tells Office
365 PowerShell to take the results of one command and send it to the next command. Here is an example
command that displays only those user accounts that have an unspecified usage location:

Get-AzureADUser | Where-Object {$_.UsageLocation -eq $Null}

This command instructs Office 365 PowerShell to:


Get all of the information on the user accounts ( Get-AzureADUser ) and send it to the next command ( | ).
Find all of the user accounts that have an unspecified usage location ( Where-Object {$_.UsageLocation -
eq $Null} ). Inside the braces, the command instructs Office 365 PowerShell to only find the set of
accounts in which the UsageLocation user account property ( $_.UsageLocation ) is not specified ( -eq
$Null ).
The UsageLocation property is only one of many properties associated with a user account. To see all of the
properties for user accounts, use the Select-Object cmdlet and the wildcard character () to display them all for a
specific user account, one page at a time ( **More* ). Here is an example:

Get-AzureADUser -ObjectID "[email protected]" | Select-Object * | More

For example, City is the name of a user account property. This means you can use the following command to list
all of the user accounts for users living in London:

Get-AzureADUser | Where-Object {$_.City -eq "London"}


TIP
The syntax for the Where-Object cmdlet shown in these examples is Where-Object {$_. [user account property name]
[comparison operator] [value] }.> [comparison operator] is -eq for equals, -ne for not equals, -lt for less than, -gt for greater
than, and others> [value] is typically a string (a sequence of letters, numbers, and other characters), a numerical value, or
$Null for unspecified> SeeWhere-Object for more information.

Select the user account properties to display


The Get-AzureADUser cmdlet by default displays the ObjectID, DisplayName, and UserPrincipalName
properties of user accounts. If you need additional properties, such as the department the user works for and the
country/region where the user uses Office 365 services, you can run Get-AzureADUser in combination with the
Select-Object cmdlet to specify the list of user account properties. Here is an example:

Get-AzureADUser | Select-Object DisplayName,Department,UsageLocation

This command instructs Office 365 PowerShell to:


Get all of the information on the user accounts ( Get-AzureADUser ) and send it to the next command ( | ).
Display only the user account name, department, and usage location ( Select-Object DisplayName,
Department, UsageLocation ).
To be more selective about the list of accounts to display, you can also use the Where-Object cmdlet. Here is an
example command that displays only those user accounts that have an unspecified usage location:

Get-AzureADUser | Where-Object {$_.UsageLocation -eq $Null} | Select-Object DisplayName, Department,


UsageLocation

This command instructs Office 365 PowerShell to:


Get all of the information on the user accounts ( Get-AzureADUser ) and send it to the next command ( | ).
Find all of the user accounts that have an unspecified usage location ( Where-Object {$_.UsageLocation -
eq $Null} ) and send the resulting information to the next command ( | ). Inside the braces, the command is
instructing Office 365 PowerShell to only find the set of accounts in which the UsageLocation user account
property ( $_.UsageLocation ) is not specified ( -eq $Null ).
Display only the user account name, department, and usage location ( Select-Object DisplayName,
Department, UsageLocation ).

New to Office 365?


TIP
New to Office 365?
Discover free video courses for Office 365 admins and IT pros, brought to you by LinkedIn Learning.

See also
Manage user accounts and licenses with Office 365 PowerShell
Manage Office 365 with Office 365 PowerShell
Getting started with Office 365 PowerShell
Configure user account properties with Office 365
PowerShell
2/13/2018 • 6 min to read • Edit Online

Summary: Use Office 365 PowerShell to configure properties of individual or multiple user accounts in your
Office 365 tenant.
Although you can use the Office 365 Admin center to configure properties for the user accounts of your Office
365 tenant, you can also use Office 365 PowerShell and do some things that the Office 365 Admin center cannot.

Before you begin


The procedures in this topic require you to connect to Office 365 PowerShell. For instructions, see Connect to
Office 365 PowerShell.

Change properties for a specific user account


To configure properties for a specific user account, you use the Set-MsolUser cmdlet and specify the properties to
set or change. This example command changes Belinda Newman's usage location to France:

Set-MsolUser -UserPrincipalName "[email protected]" -UsageLocation "FR"

You identify the account with the -UserPrincipalName parameter and set or change specific properties with
additional parameters. Here is a list of the most common parameters.
-City "<city name>"
-Country "<country name>"
-Department "<department name>"
-DisplayName "<full user name>"
-Fax "<fax number>"
-FirstName "<user first name>"
-LastName "<user last name>"
-MobilePhone "<mobile phone number>"
-Office "<office location>"
-PhoneNumber "<office phone number>"
-PostalCode "<postal code>"
-PreferredLanguage "<language>"
-State "<state name>"
-StreetAddress "<street address>"
-Title "<title name>"
-UsageLocation "<2-character country or region code>"
This is the ISO 3166-1 alpha-2 (A2) two-letter country or region code.
See Set-MsolUser for additional parameters.
To see the User Principal Names of all your users, run the following command.

Get-MSolUser | Sort-Object UserPrincipalName | Select-Object UserPrincipalName | More

This command instructs Office 365 PowerShell to:


Get all of the information on the user accounts ( Get-MsolUser ) and send it to the next command ( | ).
Sort the list of User Principal Names alphabetically ( Sort-Object UserPrincipalName ) and send it to the
next command ( | ).
Display just the User Principal Name property for each account ( Select-Object UserPrincipalName ).
Display them one screen at a time ( More ).
This command will list all of your accounts. If you want to display the User Principal Name for an account based on
its display name (first and last name), fill in the $userName variable below (removing the < and > characters), and
then run the following commands:

$userName="<Display name>"
Write-Host (Get-MsolUser | where {$_.DisplayName -eq $userName}).UserPrincipalName

This example displays the User Principal Name for the user named Caleb Sills.

$userName="Caleb Sills"
Write-Host (Get-MsolUser | where {$_.DisplayName -eq $userName}).UserPrincipalName

By using a $upn variable, you can make changes to individual accounts based on their display name. Here is an
example of setting Belinda Newman's usage location to France, but specifying her display name rather than her
User Principal Name:

$userName="<Display name>"
$upn=(Get-MsolUser | where {$_.DisplayName -eq $userName}).UserPrincipalName
Set-MsolUser -UserPrincipalName $upn -UsageLocation "FR"

Change properties for all user accounts


To change properties for all users, you can use the combination of the Get-MsolUser and Set-MsolUser cmdlets.
The following example changes the usage location for all users to France:

Get-MsolUser | Set-MsolUser -UsageLocation "FR"

This command instructs Office 365 PowerShell to:


Get all of the information on the user accounts ( Get-MsolUser ) and send it to the next command ( | ).
Set the user location to France ( Set-MsolUser -UsageLocation "FR" ).
Change properties for a specific set of user accounts
To change properties for a specific set of user account, you can use the combination of the Get-MsolUser, Where-
Object, and Set-MsolUser cmdlets. The following example changes the usage location for all the users in the
Accounting department to France:

Get-MsolUser | Where-Object {$_.Department -eq "Accounting"} | Set-MsolUser -UsageLocation "FR"

This command instructs Office 365 PowerShell to:


Get all of the information on the user accounts ( Get-MsolUser ) and send it to the next command ( | ).
Find all of the user accounts that have their Department property set to "Accounting" ( Where-Object
{$_.Department -eq "Accounting"} ) and send the resulting information to the next command ( | ).
Set the user location to France ( Set-MsolUser -UsageLocation "FR" ).
Display them one screen at a time ( More ).

Use the Azure Active Directory V2 PowerShell module to configure


user account properties
To configure properties for user accounts with the Azure Active Directory V2 PowerShell module, you use the Set-
AzureADUser cmdlet and specify the properties to set or change. But first, you must connect to your subscription.
For the instructions, see Connect with the Azure Active Directory V2 PowerShell module.
Change properties for a specific user account
This example command changes Belinda Newman's usage location to France:

Set-AzureADUser -ObjectID "[email protected]" -UsageLocation "FR"

You identify the account with the -ObjectID parameter and set or change specific properties with additional
parameters. Here is a list of the most common parameters.
-Department "<department name>"
-DisplayName "<full user name>"
-FacsimilieTelephoneNumber "<fax number>"
-GivenName "<user first name>"
-Surname "<user last name>"
-Mobile "<mobile phone number>"
-JobTitle "<job title>"
-PreferredLanguage "<language>"
-StreetAddress "<street address>"
-City "<city name>"
-State "<state name>"
-PostalCode "<postal code>"
-Country "<country name>"
-TelephoneNumber "<office phone number>"
-UsageLocation "<2-character country or region code>"
This is the ISO 3166-1 alpha-2 (A2) two-letter country or region code.
See Set-AzureADUser for additional parameters.
To display the User Principal Name for your user accounts, run the following command.

Get-AzureADUser | Sort-Object UserPrincipalName | Select-Object UserPrincipalName | More

This command instructs Office 365 PowerShell to:


Get all of the information on the user accounts ( Get-AzureADUser ) and send it to the next command ( | ).
Sort the list of User Principal Names alphabetically ( Sort-Object UserPrincipalName ) and send it to the
next command ( | ).
Display just the User Principal Name property for each account ( Select-Object UserPrincipalName ).
Display them one screen at a time ( More ).
This command will list all of your accounts. If you want to display the User Principal Name for an account based on
its display name (first and last name), fill in the $userName variable below (removing the < and > characters), and
then run the following commands:

$userName="<Display name>"
Write-Host (Get-AzureADUser | where {$_.DisplayName -eq $userName}).UserPrincipalName

This example displays the User Principal Name for the user named Caleb Sills.

$userName="Caleb Sills"
Write-Host (Get-AzureADUser | where {$_.DisplayName -eq $userName}).UserPrincipalName

By using a $upn variable, you can make changes to individual accounts based on their display name. Here is an
example of setting Belinda Newman's usage location to France, but specifying her display name rather than her
User Principal Name:

$userName="Belinda Newman"
$upn=(Get-AzureADUser | where {$_.DisplayName -eq $userName}).UserPrincipalName
Set-AzureADUser -ObjectID $upn -UsageLocation "FR"

Change properties for all user accounts


To change properties for all users, you can use the combination of the Get-AzureADUser and Set-AzureADUser
cmdlets. The following example changes the usage location for all users to France:

Get-AzureADUser | Set-AzureADUser -UsageLocation "FR"

This command instructs Office 365 PowerShell to:


Get all of the information on the user accounts ( Get-AzureADUser ) and send it to the next command ( | ).
Set the user location to France ( Set-AzureADUser -UsageLocation "FR" ).
Change properties for a specific set of user accounts
To change properties for a specific set of user account, you can use the combination of the Get-AzureADUser,
Where, and Set-AzureADUser cmdlets. The following example changes the usage location for all the users in the
Accounting department to France:

Get-AzureADUser | Where-Object {$_.Department -eq "Accounting"} | Set-AzureADUser -UsageLocation "FR"

This command instructs Office 365 PowerShell to:


Get all of the information on the user accounts ( Get-AzureADUser ) and send it to the next command ( | ).
Find all of the user accounts that have their Department property set to "Accounting" ( Where
{$_.Department -eq "Accounting"} ) and send the resulting information to the next command ( | ).
Set the user location to France ( Set-AzureADUser -UsageLocation "FR" ).

See also
Manage user accounts and licenses with Office 365 PowerShell
Manage Office 365 with Office 365 PowerShell
Getting started with Office 365 PowerShell
Manage SharePoint Online with Office 365
PowerShell
5/7/2018 • 1 min to read • Edit Online

Summary: Use Office 365 PowerShell to manage SharePoint Online users, groups, and site groups.
One of the primary tasks of any SharePoint Online administrator is managing sites, site groups, and users.
Although you can accomplish some of these tasks in the Office 365 admin center, other tasks are much quicker
and easier in Office 365 PowerShell. For more information, see the following topics:
Connect to SharePoint Online PowerShell
Create SharePoint Online sites and add users with Office 365 PowerShell
Manage SharePoint Online users and groups with Office 365 PowerShell
Manage SharePoint Online site groups with Office 365 PowerShell

See also
Manage Office 365 with Office 365 PowerShell
Getting started with Office 365 PowerShell
Create SharePoint Online sites and add users with
Office 365 PowerShell
5/3/2018 • 4 min to read • Edit Online

Summary: Use Office 365 PowerShell to create new SharePoint Online sites, and then add users and groups to
those sites.
When you use Office 365 PowerShell to create SharePoint Online sites and add users, you can quickly and
repeatedly perform tasks much faster than you can in the Office 356 admin center. You can also perform tasks that
are not possible to perform in the Office 356 admin center.

Before you begin


The procedures in this topic require you to connect to SharePoint Online. For instructions, see Connect to
SharePoint Online PowerShell

Step 1: Create new site collections using Office 365 PowerShell


Create multiple sites using Office 365 PowerShell and a .csv file that you create using the example code provided
and Notepad. For this procedure, you’ll be replacing the placeholder information shown in brackets with your own
site- and tenant-specific information. This process allows you to create a single file and run a single Office 365
PowerShell command that uses that file. This makes the actions taken both repeatable and portable and eliminates
many, if not all, errors that can come from typing long commands into the SharePoint Online Management Shell.
There are two parts to this procedure. First you’ll create a .csv file, and then you’ll reference that .csv file using
Office 365 PowerShell, which will use its contents to create the sites.
The Office 365 PowerShell cmdlet imports the .csv file and pipes it to a loop inside the curly brackets that reads
the first line of the file as column headers. The Office 365 PowerShell cmdlet then iterates through the remaining
records, creates a new site collection for each record, and assigns properties of the site collection according to the
column headers.
Create a .csv file
1. Open Notepad, and paste the following text block into it:
Owner,StorageQuota,Url,ResourceQuota,Template,TimeZoneID,Name
[email protected],100,https://tenant.sharepoint.com/sites/TeamSite01,25,EHS#1,10,Contoso Team
Site [email protected],100,https://tenant.sharepoint.com/sites/Blog01,25,BLOG#0,10,Contoso Blog
[email protected],150,https://tenant.sharepoint.com/sites/Project01,25,PROJECTSITE#0,10,Project
Alpha
[email protected],150,https://tenant.sharepoint.com/sites/Community01,25,COMMUNITY#0,10,Community
Site
Where tenant is the name of your tenant, and owner is the user name of the user on your tenant to whom you
want to grant the role of primary site collection administrator.
(You can press Ctrl+H when you use Notepad to bulk replace faster.)
2. Save the file on your desktop as SiteCollections.csv.

TIP
Before you use this or any other .csv or Windows PowerShell script file, it is good practice to make sure that there are
no extraneous or nonprinting characters. Open the file in Word, and in the ribbon, click the paragraph icon to show
nonprinting characters. There should be no extraneous nonprinting characters. For example, there should be no
paragraph marks beyond the final one at the end of the file.
Run the Windows PowerShell command
1. At the Windows PowerShell prompt, type or copy and paste the following cmdlet, and press Enter:
Import-Csv C:\users\MyAlias\desktop\SiteCollections.csv | ForEach-Object {New-SPOSite -Owner $_.Owner -
StorageQuota $_.StorageQuota -Url $_.Url -NoWait -ResourceQuota $_.ResourceQuota -Template $_.Template -
TimeZoneID $_.TimeZoneID -Title $_.Name}
Where MyAlias equals your user alias.
2. Wait for the Windows PowerShell prompt to reappear. It might take a minute or two.
3. At the Windows PowerShell prompt, type or copy and paste the following cmdlet, and press Enter:
Get-SPOSite -Detailed | Format-Table -AutoSize
4. Note the new site collections in the list. You should see the following site collections: contosotest,
TeamSite01, Blog01, and Project01.
That’s it. You’ve created multiple site collections using the .csv file you created and a single Windows PowerShell
cmdlet. You’re now ready to create and assign users to these sites.

Step 2: Add users and groups


Now you’re going to create users and add them to a site collection group. You will then use a .csv file to bulk
upload new groups and users.
The following procedures assume that you successfully created the site collections contosotest, TeamSite01,
Blog01, and Project01.
Create .csv and .ps1 files
1. Open Notepad, and paste the following text block into it:
Site,Group,PermissionLevels https://tenant.sharepoint.com/sites/contosotest,Contoso Project Leads,Full
Control https://tenant.sharepoint.com/sites/contosotest,Contoso Auditors,View Only
https://tenant.sharepoint.com/sites/contosotest,Contoso Designers,Design
https://tenant.sharepoint.com/sites/TeamSite01,XT1000 Team Leads,Full Control
https://tenant.sharepoint.com/sites/TeamSite01,XT1000 Advisors,Edit
https://tenant.sharepoint.com/sites/Blog01,Contoso Blog Designers,Design
https://tenant.sharepoint.com/sites/Blog01,Contoso Blog Editors,Edit
https://tenant.sharepoint.com/sites/Project01,Project Alpha Approvers,Full Control
Where tenant equals your tenant name.
2. Save the file to your desktop as GroupsAndPermissions.csv.
3. Open a new instance of Notepad, and paste the following text block into it:
Group,LoginName,Site Contoso Project
Leads,[email protected],https://tenant.sharepoint.com/sites/contosotest Contoso
Auditors,[email protected],https://tenant.sharepoint.com/sites/contosotest Contoso
Designers,[email protected],https://tenant.sharepoint.com/sites/contosotest XT1000 Team
Leads,[email protected],https://tenant.sharepoint.com/sites/TeamSite01 XT1000
Advisors,[email protected],https://tenant.sharepoint.com/sites/TeamSite01 Contoso Blog
Designers,[email protected],https://tenant.sharepoint.com/sites/Blog01 Contoso Blog
Editors,[email protected],https://tenant.sharepoint.com/sites/Blog01 Project Alpha
Approvers,[email protected],https://tenant.sharepoint.com/sites/Project01
Where tenant equals your tenant name, and username equals the user name of an existing user.
4. Save the file to your desktop as Users.csv.
5. Open a new instance of Notepad, and paste the following text block into it:
Import-Csv C:\users\MyAlias\desktop\GroupsAndPermissions.csv | ForEach-Object {New-SPOSiteGroup -Group
$_.Group -PermissionLevels $_.PermissionLevels -Site $_.Site} Import-Csv C:\users\MyAlias\desktop\Users.csv
| where {Add-SPOUser -Group $_.Group –LoginName $_.LoginName -Site $_.Site}
Where MyAlias equals the user name of the user that is currently logged on.
6. Save the file to your desktop as UsersAndGroups.ps1. This is a simple Windows PowerShell script.
You’re now ready to run the UsersAndGroup.ps1 script to add users and groups to multiple site collections.
Run UsersAndGroups.ps1 script
1. Return to the SharePoint Online Management Shell.
2. At the Windows PowerShell prompt, type or copy and paste the following line, and press Enter:
Set-ExecutionPolicy Bypass
3. At the confirmation prompt, press Y.
4. At the Windows PowerShell prompt, type or copy and paste the following, and press Enter:
c:\users\MyAlias\desktop\UsersAndGroups.ps1
Where MyAlias equals your user name.
5. Wait for the prompt to return before moving on. You will first see the groups appear as they are created. Then
you will see the group list repeated as users are added.

See also
Connect to SharePoint Online PowerShell
Manage SharePoint Online site groups Office 365 PowerShell
Manage Office 365 with Office 365 PowerShell
Getting started with Office 365 PowerShell
Manage SharePoint Online users and groups with
Office 365 PowerShell
5/7/2018 • 7 min to read • Edit Online

Summary: Use Office 365 PowerShell to manage SharePoint Online users, groups, and sites.
If you are a SharePoint Online administrator who works with large lists of user accounts or groups and wants an
easier way to manage them, you can use Office 365 PowerShell.

Before you begin


The procedures in this topic require you to connect to SharePoint Online. For instructions, see Connect to
SharePoint Online PowerShell

Get a list of sites, groups, and users


Before we start to manage users and groups, you need to get lists of your sites, groups, and users. You can then
use this information to work through the example in this article.
Get a list of sites
Get a list of the sites in your tenant with this command:

Get-SPOSite

Get a list of groups


Get a list of the groups in your tenant with this command:

Get-SPOSite | ForEach {Get-SPOSiteGroup -Site $_.Url} | Format-Table

Get a list of users


Get a list of the users in your tenant with this command:

Get-SPOSite | ForEach {Get-SPOUser -Site $_.Url}

Add a user to the Site Collection Administrators group


You use the Set-SPOUser command to add a user to the list of Site Collection Administrators on a site collection.
This is how the syntax looks:

$tenant = "<tenant name, such as litwareinc for litwareinc.onmicrosoft.com>"


$site = "<site name>"
$user = "<user account name, such as opalc>"
Set-SPOUser -Site https://$tenant.sharepoint.com/sites/$site -LoginName $user@$tenant.onmicrosoft.com -
IsSiteCollectionAdmin $true

To use these commands, replace replace everything within the quotes, including the < and > characters, with the
correct names.
For example, this set of commands adds Opal Castillo (user name opalc) the list of Site Collection Administrators
on the ContosoTest site collection in the contoso1 tenancy:

$tenant = "contoso1"
$site = "contosotest"
$user = "opalc"
Set-SPOUser -Site https://$tenant.sharepoint.com/sites/$site -LoginName $user@$tenant.onmicrosoft.com -
IsSiteCollectionAdmin $true

You can copy and paste these commands into Notepad, change the variable values for $tenant, $site, and $user to
actual values from your environment, and then paste this into your SharePoint Online Management Shell window
to run them.

Add a user to other Site Collection Administrators groups


In this task, we'll use the Add-SPOUser command to add a user to a SharePoint group on a site collection.

$tenant = "<tenant name, such as litwareinc for litwareinc.onmicrosoft.com>"


$site = "<site name>"
$user = "<user account name, such as opalc>"
$group = "<group name name, such as Auditors>"
Add-SPOUser -Group $group -LoginName $user@$tenant.onmicrosoft.com -Site
https://$tenant.sharepoint.com/sites/$site

For example, let’s add Glen Rife (user name glenr) to the Auditors group on the ContosoTest site collection in the
contoso1 tenancy:

$tenant = "contoso1"
$site = "contosotest"
$user = "glenr"
$group = "Auditors"
Add-SPOUser -Group $group -LoginName $user@$tenant.onmicrosoft.com -Site
https://$tenant.sharepoint.com/sites/$site

Create a site collection group


You use the Set-SPOSiteGroup command to create a new SharePoint group and add it to the ContosoTest site
collection.

$tenant = "<tenant name, such as litwareinc for litwareinc.onmicrosoft.com>"


$site = "<site name>"
$group = "<group name name, such as Auditors>"
$level = "<permission level, such as View Only>"
New-SPOSiteGroup -Group $group -PermissionLevels $level -Site https://$tenant.sharepoint.com/sites/$site

Group properties, such as permission levels, can be updated later by using the Set-SPOSiteGroup cmdlet.
For example, let’s add the Auditors group with View Only permissions to the Contoso Test site collection in the
contoso1 tenancy:

$tenant = "contoso1"
$site = "Contoso Test"
$group = "Auditors"
$level = "View Only"
New-SPOSiteGroup -Group $group -PermissionLevels $level -Site https://$tenant.sharepoint.com/sites/$site
Remove users from a group
Sometimes you have to remove a user from a site or even all sites. Perhaps the employee moves from one division
to another or leaves the company. You can do this for one employee easily in the UI, but this is not easily done
when you have to move a complete division from one site to another.
However by using the SharePoint Online Management Shell and CSV files, this is fast and easy. In this task, you'll
use Windows PowerShell to remove a user from a site collection security group. Then you'll use a CSV file and
remove lots of users from different sites.
We'll be using the Remove-SPOUser command to remove a single Office 365 user from a site collection group
just so we can see the command syntax. Here is how the syntax looks:

$tenant = "<tenant name, such as litwareinc for litwareinc.onmicrosoft.com>"


$site = "<site name>"
$user = "<user account name, such as opalc>"
$group = "<group name name, such as Auditors>"
Remove-SPOUser -LoginName $user@$tenant.onmicrosoft.com -Site https://$tenant.sharepoint.com/sites/$site -
Group $group

For example, let’s remove Bobby Overby from the site collection Auditors group in the Contoso Test site collection
in the contoso1 tenancy:

$tenant = "contoso1"
$site = "contosotest"
$user = "bobbyo"
$group = "Auditors"
Remove-SPOUser -LoginName $user@$tenant.onmicrosoft.com -Site https://$tenant.sharepoint.com/sites/$site -
Group $group

Suppose we wanted to remove Bobby from all the groups he is currently in. Here is how we would do that:

$tenant = "contoso1"
$user = "bobbyo"
Get-SPOSite | ForEach {Get-SPOSiteGroup –Site $_.Url} | ForEach {Remove-SPOUser -LoginName
$user@$tenant.onmicrosoft.com -Site &_.Url}

WARNING
This is just an example. You should not run this command unless you really have to remove a user from every group, for
example if the user leaves the company.

Automate management of large lists of users and groups


To add a large number of accounts to SharePoint sites and give them permissions, you can use the Office 365
admin center, individual PowerShell commands, or PowerShell an a CSV file. Of these choices, the CSV file is the
fastest way to automate this task.
The basic process is to create a CSV file that has headers (columns) that correspond to the parameters that the
Windows PowerShell script needs. You can easily create such a list in Excel and then export it as a CSV file. Then,
you use a Windows PowerShell script to iterate through records (rows) in the CSV file, adding the users to groups
and the groups to sites.
For example, let’s create a CSV file to define a group of site collections, groups, and permissions. Next, we will
create a CSV file to populate the groups with users. Finally, we will create and run a simple Windows PowerShell
script that creates and populates the groups.
The first CSV file will add one or more groups to one or more site collections and will have this structure:

Site,Group,PermissionLevels

Item:

https://tenant.sharepoint.com/sites/site,group,level

Here is an example file:

Site,Group,PermissionLevels
https://contoso1.sharepoint.com/sites/contosotest,Contoso Project Leads,Full Control
https://contoso1.sharepoint.com/sites/contosotest,Contoso Auditors,View Only
https://contoso1.sharepoint.com/sites/contosotest,Contoso Designers,Design
https://contoso1.sharepoint.com/sites/TeamSite01,XT1000 Team Leads,Full Control
https://contoso1.sharepoint.com/sites/TeamSite01,XT1000 Advisors,Edit
https://contoso1.sharepoint.com/sites/Blog01,Contoso Blog Designers,Design
https://contoso1.sharepoint.com/sites/Blog01,Contoso Blog Editors,Edit
https://contoso1.sharepoint.com/sites/Project01,Project Alpha Approvers,Full Control

The second CSV file will add one or more users to one or more groups and will have this structure:
Header:

Group,LoginName,Site

Item:

group,login,https://tenant.sharepoint.com/sites/site

Here is an example file:

Group,LoginName,Site
Contoso Project Leads,[email protected],https://contoso1.sharepoint.com/sites/contosotest
Contoso Auditors,[email protected],https://contoso1.sharepoint.com/sites/contosotest
Contoso Designers,[email protected],https://contoso1.sharepoint.com/sites/contosotest
XT1000 Team Leads,[email protected],https://contoso1.sharepoint.com/sites/TeamSite01
XT1000 Advisors,[email protected],https://contoso1.sharepoint.com/sites/TeamSite01
Contoso Blog Designers,[email protected],https://contoso1.sharepoint.com/sites/Blog01
Contoso Blog Editors,[email protected],https://contoso1.sharepoint.com/sites/Blog01
Project Alpha Approvers,[email protected],https://contoso1.sharepoint.com/sites/Project01

For the next step, you must have the two CSV files saved to your drive. Here are example commands that use both
CSV files and to add permissions and group membership:

Import-Csv C:\O365Admin\GroupsAndPermissions.csv | ForEach {New-SPOSiteGroup -Group $_.Group -PermissionLevels


$_.PermissionLevels -Site $_.Site}
Import-Csv C:\O365Admin\Users.csv | ForEach {Add-SPOUser -Group $_.Group –LoginName $_.LoginName -Site
$_.Site}

The script imports the CSV file contents and uses the values in the columns to populate the parameters of the
New-SPOSiteGroup and Add-SPOUser commands. In our example, we are saving this to theO365Admin folder
on drive C, but you can save it wherever you want.
Now, let’s remove a bunch of people for several groups in different sites using the same CSV file. Here is an
example command:

Import-Csv C:\O365Admin\Users.csv | ForEach {Remove-SPOUser -LoginName $_.LoginName -Site $_.Site -Group


$_.Group}

Generate user reports


You might want to get a simple report for a few sites and display the users for those sites, their permission level,
and other properties. This is how the syntax looks:

$tenant = "<tenant name, such as litwareinc for litwareinc.onmicrosoft.com>"


$site = "<site name>"
Get-SPOUser -Site https://$tenant.sharepoint.com/sites/$site | select * | Format-table -Wrap -AutoSize | Out-
File c\UsersReport.txt -Force -Width 360 -Append

This will grab the data for these three sites and write them to a text file on your local drive. Note that the parameter
–Append will add new content to an existing file.
For example, let's run a report on the ContosoTest, TeamSite01, and Project01 sites for the Contoso1 tenant:

$tenant = "contoso1"
$site = "contosotest"
Get-SPOUser -Site https://$tenant.sharepoint.com/sites/$site | Format-Table -Wrap -AutoSize | Out-File
c:\UsersReport.txt -Force -Width 360 -Append
$site = "TeamSite01"
Get-SPOUser -Site https://$tenant.sharepoint.com/sites/$site |Format-Table -Wrap -AutoSize | Out-File
c:\UsersReport.txt -Force -Width 360 -Append
$site = "Project01"
Get-SPOUser -Site https://$tenant.sharepoint.com/sites/$site | Format-Table -Wrap -AutoSize | Out-File
c:\UsersReport.txt -Force -Width 360 -Append

Note that we had to change only the $site variable. The $tenant variable keeps its value through all three runs of
the command.
However, what if you wanted to do this for every site? You can do this without having to type all those websites by
using this command:

Get-SPOSite | ForEach {Get-SPOUser –Site $_.Url} | Format-Table -Wrap -AutoSize | Out-File c:\UsersReport.txt
-Force -Width 360 -Append

This report is fairly simple, and you can add more code to create more specific reports or reports that include
more detailed information. But this should give you an idea of how to use the SharePoint Online Management
Shell to manage users in the SharePoint Online environment.

See also
Connect to SharePoint Online PowerShell
Manage SharePoint Online with Office 365 PowerShell
Manage Office 365 with Office 365 PowerShell
Getting started with Office 365 PowerShell
Manage SharePoint Online site groups with Office
365 PowerShell
5/7/2018 • 2 min to read • Edit Online

Summary: Use Office 365 PowerShell to manage SharePoint Online site groups.
Although you can use the Office 365 admin center, you can also use Office 365 PowerShell to manage your
SharePoint Online site groups.

Before you begin


The procedures in this article require you to connect to SharePoint Online. For instructions, see Connect to
SharePoint Online PowerShell.

View SharePoint Online with Office 365 PowerShell


The SharePoint Online admin center has some easy-to-use methods for managing site groups. For example,
suppose you want to look at the groups, and the group members, for the
https://litwareinc.sharepoint.com/sites/finance site. Here’s what you have to do to:
1. From the Office 365 admin center, click Resources > Sites, and then click the URL of the site.
2. In the site collection dialog box, click Go to this site.
3. On the site page, click the Settings icon (located in the upper right-hand corner of the page) and then click Site
settings:

4. On the Site Settings page, click Sites permissions under Users and Permissions.
And then repeat the process for the next site you want to look at.
To get a list of the groups with Office 365 PowerShell, you would use the following command set:
$siteURL = "https://litwareinc.sharepoint.com/sites/finance"
$x = Get-SPOSiteGroup -Site $siteURL
foreach ($y in $x)
{
Write-Host $y.Title -ForegroundColor "Yellow"
Get-SPOSiteGroup -Site $siteURL -Group $y.Title | Select-Object -ExpandProperty Users
Write-Host
}

There are two ways to run this command set in the SharePoint Online Management Shell command prompt:
Copy the commands into Notepad (or another text editor), modify the value of the $siteURL variable, select
the commands, and then paste them into the SharePoint Online Management Shell command prompt. When
you do, PowerShell will stop at a >> prompt. Press Enter to execute the foreach command.
Copy the commands into Notepad (or another text editor), modify the value of the $siteURL variable, and then
save this text file with a name and the .ps1 extension in a suitable folder. Next, run the script from the
SharePoint Online Management Shell command prompt by specifying its path and file name. Here is an
example command:

C:\Scripts\SiteGroupsAndUsers.ps1

In both cases, you should see something similar to this:

These are all the groups that have been created for the site https://litwareinc.sharepoint.com/sites/finance, as well
as all the users assigned to those groups. The group names are in yellow to help you separate group names from
their members.
As another example, here is a command set that lists the groups, and all the group memberships, for all of your
SharePoint Online sites.
$x = Get-SPOSite
foreach ($y in $x)
{
Write-Host $y.Url -ForegroundColor "Yellow"
$z = Get-SPOSiteGroup -Site $y.Url
foreach ($a in $z)
{
$b = Get-SPOSiteGroup -Site $y.Url -Group $a.Title
Write-Host $b.Title -ForegroundColor "Cyan"
$b | Select-Object -ExpandProperty Users
Write-Host
}
}

See also
Connect to SharePoint Online PowerShell
Create SharePoint Online sites and add users with Office 365 PowerShell
Manage SharePoint Online users and groups with Office 365 PowerShell
Manage Office 365 with Office 365 PowerShell
Getting started with Office 365 PowerShell
Manage Exchange Online with Office 365 PowerShell
2/13/2018 • 1 min to read • Edit Online

Summary: Use Office 365 PowerShell to manage Microsoft Exchange Online, including displaying mailbox
configuration and advanced reporting.
One of the primary tasks of any Microsoft Exchange Online administrator is managing mailboxes and getting
reports on them. Although you can accomplish some of these tasks in the Office 365 admin center, other tasks are
much quicker and easier in Office 365 PowerShell. For more information, see the following topics:
Display Exchange Online mailbox information with Office 365 PowerShell
Display Exchange Online reports with Office 365 PowerShell
Determine which cmdlets are available to Exchange Online administrators with Office 365 PowerShell

See also
Manage Office 365 with Office 365 PowerShell
Getting started with Office 365 PowerShell
Use PowerShell for email migration to Office 365
1/10/2018 • 1 min to read • Edit Online

Summary: Learn how to migrate email to Office 365 using Windows PowerShell.
When administrators first set up Office 365, many of them migrate email from existing systems. You can also do
this by using the Office 365 administration user interface. You can also use Windows PowerShell to migrate email.

Office 365 licensing and Windows PowerShell


Use Windows PowerShell to migrate email to Office 365.
Use PowerShell to perform a cutover migration to Office 365
Use PowerShell to perform an IMAP migration to Office 365
Use PowerShell to perform a staged migration to Office 365

See also
Manage Office 365 with Office 365 PowerShell
Getting started with Office 365 PowerShell
Manage SharePoint Online with Office 365 PowerShell
Use Windows PowerShell to create reports in Office 365
Advantages of using Windows PowerShell to manage Office 365
Windows PowerShell in Office 365 technical reference
Office 365 Licensing and Windows PowerShell
Use PowerShell to perform a cutover migration to
Office 365
5/18/2018 • 9 min to read • Edit Online

Summary: Learn how to use Windows PowerShell to perform a cutover migration to Office 365.
You can migrate the contents of user mailboxes from a source email system to Office 365 all at once by using a
cutover migration. This article walks you through the tasks for an email cutover migration by using Exchange
Online PowerShell.
By reviewing the topic, What you need to know about a cutover email migration to Office 365, you can get an
overview of the migration process. When you're comfortable with the contents of that article, use this one to begin
migrating mailboxes from one email system to another.

NOTE
You can also use the Exchange admin center to perform a cutover migration. See Perform a cutover migration of email to
Office 365.

What do you need to know before you begin?


Estimated time to complete this task: 2-5 minutes to create a migration batch. After the migration batch is started,
the duration of the migration will vary based on the number of mailboxes in the batch, the size of each mailbox,
and your available network capacity. For information about other factors that affect how long it takes to migrate
mailboxes to Office 365, see Migration Performance.
You need to be assigned permissions before you can perform this procedure or procedures. To see what
permissions you need, see the "Migration" entry in a table in the Recipients Permissions topic.
To use the Exchange Online PowerShell cmdlets, you need to sign in and import the cmdlets into your local
Windows PowerShell session. See Connect to Exchange Online using remote PowerShell for instructions.
For a full list of migration commands, see Move and migration cmdlets.

Migration steps
Step 1: Prepare for a cutover migration
Add your on-premises Exchange organization as an accepted domain of your Office 365
organization. The migration service uses the SMTP address of your on-premises mailboxes to create the
Microsoft Online Services user ID and email address for the new Office 365 mailboxes. Migration will fail if
your Exchange domain isn't an accepted domain or the primary domain of your Office 365 organization.
For more information, seeVerify your domain in Office 365.
Configure Outlook Anywhere on your on-premises Exchange server. The email migration service
uses RPC over HTTP, or Outlook Anywhere, to connect to your on-premises Exchange server. For
information about how to set up Outlook Anywhere for Exchange 2010, Exchange 2007, and Exchange
2003, see the following:
Exchange 2010: Enable Outlook Anywhere
Exchange 2007: How to Enable Outlook Anywhere
Exchange 2003: Deployment Scenarios for RPC over HTTP
How to Configure Outlook Anywhere with Exchange 2003

IMPORTANT
Your Outlook Anywhere configuration must be configured with a certificate issued by a trusted certification
authority (CA). It can't be configured with a self-signed certificate. For more information, see How to
Configure SSL for Outlook Anywhere.

Verify that you can connect to your Exchange organization using Outlook Anywhere. Try one of
these methods to test your connection settings:
Use Microsoft Outlook from outside your corporate network to connect to your on-premises
Exchange mailbox.
Use the Microsoft Exchange Remote Connectivity Analyzer to test your connection settings. Use the
Outlook Anywhere (RPC over HTTP ) or Outlook Autodiscover tests.
Run the following commands in Exchange Online PowerShell.

$Credentials = Get-Credential

Test-MigrationServerAvailability -ExchangeOutlookAnywhere -Autodiscover -EmailAddress <email address for


on-premises administrator> -Credentials $credentials

Assign an on-premises user account the necessary permissions to access mailboxes in your
Exchange organization. The on-premises user account that you use to connect to your on-premises
Exchange organization (also called the migration administrator) must have the necessary permissions to
access the on-premises mailboxes that you want to migrate to Office 365. This user account is used to
create a migration endpoint to your on-premises organization.
The following list shows the administrative privileges required to migrate mailboxes using a cutover
migration. There are three possible options.
The migration administrator must be a member of the Domain Admins group in Active Directory in
the on-premises organization.
Or
The migration administrator must be assigned the FullAccess permission for each on-premises
mailbox.
Or
The migration administrator must be assigned the Receive As permission on the on-premises
mailbox database that stores the user mailboxes.
Disable Unified Messaging. If the on-premises mailboxes you're migrating are enabled for Unified
Messaging (UM ), you have to disable UM on the mailboxes before you migrate them. You can then enable
UM on the mailboxes after the migration is complete.
Security Groups and Delegates The email migration service cannot detect whether on-premises Active
Directory groups are security groups or not, so it cannot provision any migrated groups as security groups
in Office 365. If you want to have security groups in your Office 365 tenant, you must first provision an
empty mail-enabled security group in your Office 365 tenant before starting the cutover migration.
Additionally, this migration method only moves mailboxes, mail users, mail contacts, and mail-enabled
groups. If any other Active Directory object, such as user that is not migrated to Office 365, is assigned as a
manager or delegate to an object being migrated, they must be removed from the object before you
migrate.
Step 2: Create a migration endpoint
To migrate email successfully, Office 365 needs to connect and communicate with the source email system. To do
this, Office 365 uses a migration endpoint. To create an Outlook Anywhere migration endpoint for cutover
migration, first connect to Exchange Online.
For a full list of migration commands, see Move and migration cmdlets.
Run the following commands in Exchange Online PowerShell:

$Credentials = Get-Credential

The example uses the Test-MigrationServerAvailability cmdlet to obtain and test the connection settings to the on-
premises Exchange server, and then uses those connection settings to create the migration endpoint called
"CutoverEndpoint".

$TSMA = Test-MigrationServerAvailability -ExchangeOutlookAnywhere -Autodiscover -EmailAddress


[email protected] -Credentials $credentials

New-MigrationEndpoint -ExchangeOutlookAnywhere -Name CutoverEndpoint -ConnectionSettings


$TSMA.ConnectionSettings

NOTE
The New-MigrationEndpoint cmdlet can be used to specify a database for the service to use by using the -
TargetDatabase option. Otherwise a database is randomly assigned from the Active Directory Federation Services (AD FS)
2.0 site where the management mailbox is located.

Verify it worked
In Exchange Online PowerShell, run the following command to display information about the "CutoverEndpoint"
migration endpoint:

Get-MigrationEndpoint CutoverEndpoint | Format-List EndpointType,ExchangeServer,UseAutoDiscover,Max*

Step 3: Create the cutover migration batch


You can use the New-MigrationBatch cmdlet in Exchange Online PowerShell to create a migration batch for a
cutover migration. You can create a migration batch and start it automatically by including the AutoStart
parameter. Alternatively, you can create the migration batch and then manually start it afterwards by using the
Start-MigrationBatch cmdlet. This example creates a migration batch called "CutoverBatch" and uses the
migration endpoint that was created in the previous step.

New-MigrationBatch -Name CutoverBatch -SourceEndpoint CutoverEndpoint -AutoStart

This example also creates a migration batch called "CutoverBatch" and uses the migration endpoint that was
created in the previous step. Because the AutoStart parameter isn't included, the migration batch has to be
manually started on the migration dashboard or by using Start-MigrationBatch cmdlet. As previously stated,
only one cutover migration batch can exist at a time.

New-MigrationBatch -Name CutoverBatch -SourceEndpoint CutoverEndpoint

Verify it worked
To verify that you've successfully created a migration batch for a cutover migration, run the following command in
Exchange Online PowerShell to display information about the new migration batch:

Get-MigrationBatch | Format-List

Step 4: Start the cutover migration batch


To start the migration batch in Exchange Online PowerShell, run the following command. This will create a
migration batch called "CutoverBatch".

Start-MigrationBatch -Identity CutoverBatch

Verify it worked
If a migration batch is successfully started, its status on the migration dashboard is specified as Syncing. To verify
that you've successfully started a migration batch using Exchange Online PowerShell, run the following command:

Get-MigrationBatch -Identity CutoverBatch | Format-List Status

Step 5: Route your email to Office 365


Email systems use a DNS record called an MX record to figure out where to deliver emails. During the email
migration process, your MX record was pointing to your source email system. Now that the email migration to
Office 365 is complete, it's time to point your MX record at Office 365. This helps make sure that email is delivered
to your Office 365 mailboxes. By moving the MX record, you can also you turn off your old email system when
you're ready.
For many DNS providers, there are specific instructions to change your MX record. If your DNS provider isn't
included, or if you want to get a sense of the general directions, general MX record instructions are provided as
well.
It can take up to 72 hours for the email systems of your customers and partners to recognize the changed MX
record. Wait at least 72 hours before you proceed to the next task: Step 6: Delete the cutover migration batch.
Step 6: Delete the cutover migration batch
After you change the MX record and verify that all email is being routed to Office 365 mailboxes, notify the users
that their mail is going to Office 365. After this, you can delete the cutover migration batch. Verify the following
before you delete the migration batch.
All users are using Office 365 mailboxes. After the batch is deleted, mail sent to mailboxes on the on-
premises Exchange Server isn't copied to the corresponding Office 365 mailboxes.
Office 365 mailboxes were synchronized at least once after mail began being sent directly to them. To do
this, make sure that the value in the Last Synced Time box for the migration batch is more recent than when
mail started being routed directly to Office 365 mailboxes.
To delete the "CutoverBatch" migration batch in Exchange Online PowerShell, run the following command:

Remove-MigrationBatch -Identity CutoverBatch


Section 7: Assign user licenses
Activate Office 365 user accounts for the migrated accounts by assigning licenses. If you don't assign a
license, the mailbox is disabled when the grace period ends (30 days). To assign a license in the Office 365 admin
center, seeAssign or unassign licenses for Office 365 for business.
Step 8: Complete post-migration tasks
Create an Autodiscover DNS record so users can easily get to their mailboxes. After all on-premises
mailboxes are migrated to Office 365, you can configure an Autodiscover DNS record for your Office 365
organization to enable users to easily connect to their new Office 365 mailboxes with Outlook and mobile
clients. This new Autodiscover DNS record has to use the same namespace that you're using for your Office
365 organization. For example, if your cloud-based namespace is cloud.contoso.com, the Autodiscover DNS
record you need to create is autodiscover.cloud.contoso.com.
If you keep your Exchange Server, you should also make sure that Autodiscover DNS CNAME record has to
point to Office 365 in both internal and external DNS after the migration so that the Outlook client will to
connect to the correct mailbox.

NOTE
In Exchange 2007, Exchange 2010, and Exchange 2013 you should also set
Set-ClientAccessServer AutodiscoverInternalConnectionURI to Null .

Office 365 uses a CNAME record to implement the Autodiscover service for Outlook and mobile clients.
The Autodiscover CNAME record must contain the following information:
Alias: autodiscover
Target: autodiscover.outlook.com
For more information, see Create DNS records for Office 365 when you manage your DNS records.
Decommission on-premises Exchange servers. After you've verified that all email is being routed
directly to the Office 365 mailboxes, and you no longer need to maintain your on-premises email
organization or don't plan on implementing a single sign-on (SSO ) solution, you can uninstall Exchange
from your servers and remove your on-premises Exchange organization.
For more information, see the following:
Modify or Remove Exchange 2010
How to Remove an Exchange 2007 Organization
How to Uninstall Exchange Server 2003
Use PowerShell to perform an IMAP migration to
Office 365
4/19/2018 • 9 min to read • Edit Online

Summary: Learn how to use Windows PowerShell to perform an IMAP migration to Office 365.
As part of the process of deploying Office 365, you can choose to migrate the contents of user mailboxes from an
Internet Mail Access Protocol (IMAP ) email service to Office 365. This article walks you through the tasks for an
email IMAP migration by using Exchange Online PowerShell.

NOTE
You can also use the Exchange admin center to perform an IMAP migration. See Migrate your IMAP mailboxes to Office 365.

What do you need to know before you begin?


Estimated time to complete this task: 2-5 minutes to create a migration batch. After the migration batch is started,
the duration of the migration will vary based on the number of mailboxes in the batch, the size of each mailbox,
and your available network capacity. For information about other factors that affect how long it takes to migrate
mailboxes to Office 365, see Migration Performance.
You need to be assigned permissions before you can perform this procedure or procedures. To see what
permissions you need, see the "Migration" entry in a table in the Recipients Permissions topic.
To use the Exchange Online PowerShell cmdlets, you need to sign in and import the cmdlets into your local
Windows PowerShell session. See Connect to Exchange Online using remote PowerShell for instructions.
For a full list of migration commands, see Move and migration cmdlets.
The following restrictions apply to IMAP migrations:
Only items in a user's inbox or other mail folders can be migrated. You can't migrate contacts, calendar
items, or tasks.
A maximum of 500,000 items can be migrated from a user's mailbox.
The maximum message size that can be migrated is 35 MB.

Migration steps
Step 1: Prepare for an IMAP migration
If you have a domain for you IMAP organization, add it as an accepted domain of your Office 365
organization. If you want to use the same domain you already own for your Office 365 mailboxes, you first
have to add it as an accepted domain to Office 365. After you have added it, you can create your users in
Office 365. For more information, seeVerify your domain in Office 365.
Add each user to Office 365 so that they have an Office 365 mailbox. For instructions, seeAdd users
to Office 365 for business.
Obtain the FQDN of the IMAP server. You need to provide the fully qualified domain name (FQDN )
(also called the full computer name) of the IMAP server that you will migrate mailbox data from when you
create an IMAP migration endpoint. Use an IMAP client or the PING command to verify that you can use
the FQDN to communicate with the IMAP server over the Internet.
Configure the firewall to allow IMAP connections. You might have to open ports in the firewall of the
organization that hosts the IMAP server so network traffic originating from the Microsoft datacenter during
the migration is allowed to enter the organization that hosts the IMAP server. For a list of IP addresses used
by Microsoft datacenters, see Exchange Online URLs and IP Address Ranges.
Assign the administrator account permissions to access mailboxes in your IMAP organization. If
you use administrator credentials in the CSV file, the account that you use must have the necessary
permissions to access the on-premises mailboxes. The permissions required to access user mailboxes is
determined by the particular IMAP server.
To use the Exchange Online PowerShell cmdlets, you need to sign in and import the cmdlets into your
local Windows PowerShell session. See Connect to Exchange Online using remote PowerShell for
instructions.
For a full list of migration commands, see Move and migration cmdlets.
Verify that you can connect to your IMAP server. Run the following command in Exchange Online
PowerShell to test the connection settings to your IMAP server.

Test-MigrationServerAvailability -IMAP -RemoteServer <FQDN of IMAP server> -Port <143 or 993> -Security
<None, Ssl, or Tls>

For the value of the Port parameter, it's typical to use 143 for unencrypted or Transport Layer Security
(TLS ) connections and to use 993 for SSL connections.
Step 2: Create a CSV file for an IMAP migration batch
Identify the group of users whose mailboxes you want to migrate in an IMAP migration batch. Each row in the
CSV file contains information necessary to connect to a mailbox in the IMAP messaging system.
Here are the required attributes for each user:
EmailAddress specifies the user ID for the user's Office 365 mailbox.
UserName specifies the logon name for the account to use to access the mailbox on the IMAP server.
Password specifies the password for the account in the UserName column.
Here's an example of the format for the CSV file. In this example, three mailboxes are migrated:

EmailAddress,UserName,Password
[email protected],terry.adams,1091990
[email protected],ann.beebe,2111991
[email protected],paul.cannon,3281986

For the UserName attribute, in addition to the user name, you can use the credentials of an account that has been
assigned the necessary permissions to access mailboxes on the IMAP server, the following are some of the specific
formats used for some of the IMAP servers:
Microsoft Exchange:
If you're migrating email from the IMAP implementation for Microsoft Exchange, use the format
Domain/Admin_UserName/User_UserName for the UserName attribute in the CSV file. Let's say you're
migrating email from Exchange for Terry Adams, Ann Beebe, and Paul Cannon. You have a mail administrator
account, where the user name is mailadmin and the password is P@ssw0rd. Here's what your CSV file would
look like:

EmailAddress,UserName,Password
[email protected],contoso-students/mailadmin/terry.adams,P@ssw0rd
[email protected],contoso-students/mailadmin/ann.beebe,P@ssw0rd
[email protected],contoso-students/mailadmin/paul.cannon,P@ssw0rd

Dovecot:
For IMAP servers that support Simple Authentication and Security Layer (SASL ), such as a Dovecot IMAP server,
use the format User_UserName*Admin_UserName, where the asterisk ( * ) is a configurable separator character.
Let's say you're migrating those same users' email from a Dovecot IMAP server using the administrator
credentials mailadmin and P@ssw0rd. Here's what your CSV file would look like:

EmailAddress,UserName,Password
[email protected],terry.adams*mailadmin,P@ssw0rd
[email protected],ann.beebe*mailadmin,P@ssw0rd
[email protected],paul.cannon*mailadmin,P@ssw0rd

Mirapoint:
If you're migrating email from Mirapoint Message Server, use the format #user@domain#Admin_UserName#
for the administrator credentials. To migrate email from Mirapoint using the administrator credentials mailadmin
and P@ssw0rd, your CSV file would look like this:

EmailAddress,UserName,Password
[email protected],#[email protected]#mailadmin#,P@ssw0rd
[email protected],#[email protected]#mailadmin#,P@ssw0rd
[email protected],#[email protected]#mailadmin#,P@ssw0rd

Courier IMAP:
Some source email systems, such as Courier IMAP, don't support using mailbox admin credentials to migrate
mailboxes to Office 365. Instead, you can set up your source email system to use virtual shared folders. By using
virtual shared folders, you can use the mailbox admin credentials to access user mailboxes on the source email
system. For more information about how to configure virtual shared folders for Courier IMAP, see Shared Folders.
To migrate mailboxes after you set up virtual shared folders on your source email system, you have to include the
optional attribute UserRoot in the migration file. This attribute specifies the location of each user's mailbox in the
virtual shared folder structure on the source email system. For example, the path to Terry's mailbox is
/users/terry.adams.
Here's an example of a CSV file that contains the UserRoot attribute:

EmailAddress,UserName,Password,UserRoot
[email protected],mailadmin,P@ssw0rd,/users/terry.adams
[email protected],mailadmin,P@ssw0rd,/users/ann.beebe
[email protected],mailadmin,P@ssw0rd,/users/paul.cannon

Step 3: Create an IMAP migration endpoint


To migrate email successfully, Office 365 needs to connect to and communicate with the source email system. To
do this, Office 365 uses a migration endpoint. The migration endpoint also defines the number of mailboxes to
migrate simultaneously and the number of mailboxes to synchronize simultaneously during incremental
synchronization, which occurs once every 24 hours. To create a migration end point for IMAP migration, first
connect to Exchange Online.
For a full list of migration commands, see Move and migration cmdlets.
To create the IMAP migration endpoint called "IMAPEndpoint" in Exchange Online PowerShell, run the following
command:

New-MigrationEndpoint -IMAP -Name IMAPEndpoint -RemoteServer imap.contoso.com -Port 993 -Security Ssl

You can also add parameters to specify concurrent migrations, concurrent incremental migrations, and the port to
use. The following Exchange Online PowerShell command creates an IMAP migration endpoint called
"IMAPEndpoint" that supports 50 concurrent migrations and up to 25 concurrent incremental synchronizations. It
also configures the endpoint to use port 143 for TLS encryption.

New-MigrationEndpoint -IMAP -Name IMAPEndpoint -RemoteServer imap.contoso.com -Port 143 -Security Tls -
MaxConcurrentMigrations
50 -MaxConcurrentIncrementalSyncs 25

For more information about the New-MigrationEndpoint cmdlet, seeNew -MigrationEndpoint.


Verify it worked
Run the following command in Exchange Online PowerShell to display information about the "IMAPEndpoint":

Get-MigrationEndpoint IMAPEndpoint | Format-List EndpointType,RemoteServer,Port,Security,Max*

Step 4: Create and start an IMAP migration batch


You can use the New -MigrationBatch cmdlet to create a migration batch for an IMAP migration. You can create a
migration batch and start it automatically by including the AutoStart parameter. Alternatively, you can create the
migration batch and then start it afterwards by using theStart-MigrationBatch cmdlet.
The following Exchange Online PowerShell command will automatically start the migration batch called
"IMAPBatch1" using the IMAP endpoint called "IMAPEndpoint":

New-MigrationBatch -Name IMAPBatch1 -SourceEndpoint IMAPEndpoint -CSVData


([System.IO.File]::ReadAllBytes("C:\Users\Administrator\Desktop\IMAPmigration_1.csv")) -AutoStart

Verify it worked
Run the Get-MigrationBatch cmdlet to display information about the "IMAPBatch1":

Get-MigrationBatch -Identity IMAPBatch1 | Format-List

You can also verify that the batch has started by running the following command:

Get-MigrationBatch -Identity IMAPBatch1 | Format-List Status

Step 5: Route your email to Office 365


Email systems use a DNS record called an MX record to figure out where to deliver emails. During the email
migration process, your MX record was pointing to your source email system. Now that the email migration to
Office 365 is complete, it's time to point your MX record at Office 365. This helps make sure that email is delivered
to your Office 365 mailboxes. By moving the MX record, you can also turn off your old email system when you're
ready.
For many DNS providers, there are specific instructions to change your MX record. If your DNS provider isn't
included, or if you want to get a sense of the general directions, general MX record instructions are provided as
well.
It can take up to 72 hours for the email systems of your customers and partners to recognize the changed MX
record. Wait at least 72 hours before you proceed to the next task: Step 6: Delete IMAP migration batch.
Step 6: Delete IMAP migration batch
After you change the MX record and verify that all email is being routed to Office 365 mailboxes, notify the users
that their mail is going to Office 365. After this, you can delete the IMAP migration batch. Verify the following
before you delete the migration batch.
All users are using Office 365 mailboxes. After the batch is deleted, mail sent to mailboxes on the on-
premises Exchange Server isn't copied to the corresponding Office 365 mailboxes.
Office 365 mailboxes were synchronized at least once after mail began being sent directly to them. To do
this, make sure that the value in the Last Synced Time box for the migration batch is more recent than when
mail started being routed directly to Office 365 mailboxes.
To delete the "IMAPBatch1" migration batch from Exchange Online PowerShell, run the following command:

Remove-MigrationBatch -Identity IMAPBatch1

For more information about the Remove-MigrationBatch cmdlet, seeRemove-MigrationBatch.


Verify it worked
Run the following command in Exchange Online PowerShell to display information about the "IMAPBatch1":

Get-MigrationBatch IMAPBatch1"

The command will return either the migration batch with a status of Removing, or it will return an error stating
that migration batch couldn't be found, verifying that the batch was deleted.
For more information about the Get-MigrationBatch cmdlet, seeGet-MigrationBatch.

See also
IMAP Migration Troubleshooter
Use PowerShell to perform a staged migration to
Office 365
2/8/2018 • 11 min to read • Edit Online

Summary: Learn how to use Windows PowerShell to perform a staged migration to Office 365.
You can migrate the contents of user mailboxes from a source email system to Office 365 over time using a staged
migration.
This article walks you through the tasks involved with for a staged email migration using Exchange Online
PowerShell. The topic, What you need to know about a staged email migration to Office 365, gives you an
overview of the migration process. When you're comfortable with the contents of that article, use this one to begin
migrating mailboxes from one email system to another.

NOTE
You can also use the Exchange admin center to perform staged migration. See Perform a staged migration of email to Office
365.

What do you need to know before you begin?


Estimated time to complete this task: 2-5 minutes to create a migration batch. After the migration batch is started,
the duration of the migration will vary based on the number of mailboxes in the batch, the size of each mailbox,
and your available network capacity. For information about other factors that affect how long it takes to migrate
mailboxes to Office 365, see Migration Performance.
You need to be assigned permissions before you can perform this procedure or procedures. To see what
permissions you need, see the "Migration" entry in the Recipients Permissions topic.
To use the Exchange Online PowerShell cmdlets, you need to sign in and import the cmdlets into your local
Windows PowerShell session. See Connect to Exchange Online using remote PowerShell for instructions.
For a full list of migration commands, see Move and migration cmdlets.

Migration steps
Step 1: Prepare for a staged migration
Before you migrate mailboxes to Office 365 by using a staged migration, there are a few changes you must make
to your Exchange environment.
Configure Outlook Anywhere on your on-premises Exchange Server The email migration service uses
Outlook Anywhere (also known as RPC over HTTP ), to connect to your on-premises Exchange Server. For
information about how to set up Outlook Anywhere for Exchange Server 2007, and Exchange 2003, see the
following:
Exchange 2007: How to Enable Outlook Anywhere
How to configure Outlook Anywhere with Exchange 2003
IMPORTANT
You must use a certificate issued by a trusted certification authority (CA) with your Outlook Anywhere configuration. Outlook
Anywhere can't be configured with a self-signed certificate. For more information, see How to configure SSL for Outlook
Anywhere.

Optional: Verify that you can connect to your Exchange organization using Outlook Anywhere Try one of
the following methods to test your connection settings.
Use Outlook from outside your corporate network to connect to your on-premises Exchange mailbox.
Use the Microsoft Exchange Remote Connectivity Analyzer to test your connection settings. Use the
Outlook Anywhere (RPC over HTTP ) or Outlook Autodiscover tests.
Run the following commands in Exchange Online PowerShell:

$Credentials = Get-Credential

Test-MigrationServerAvailability -ExchangeOutlookAnywhere -Autodiscover -EmailAddress <email address for


on-premises administrator> -Credentials $credentials

Set permissions The on-premises user account that you use to connect to your on-premises Exchange
organization (also called the migration administrator) must have the necessary permissions to access the
on-premises mailboxes that you want to migrate to Office 365. This user account is used when you connect
to your email system by creating a migration endpoint later in this procedure (Step 3: Create a migration
endpoint ).
To migrate the mailboxes, the admin must have one of the following permission sets:
Be a member of the Domain Admins group in Active Directory in the on-premises organization.
or
Be assigned the FullAccess permission for each on-premises mailbox and the WriteProperty permission
to modify the TargetAddress property on the on-premises user accounts.
or
Be assigned the Receive As permission on the on-premises mailbox database that stores user mailboxes
and the WriteProperty permission to modify the TargetAddress property on the on-premises user
accounts.
For instructions about how to set these permissions, see Assign permissions to migrate mailboxes to Office 365.
Disable Unified Messaging (UM ) If UM is turned on for the on-premises mailboxes you're migrating, turn off
UM before migration. Turn on UM for the mailboxes after migration is complete. For how -to steps, seedisable
unified messaging.
Use directory synchronization to create new users in Office 365. You use directory synchronization to create
all the on-premises users in your Office 365 organization.
You need to license the users after they're created. You have 30 days to add licenses after the users are created. For
steps to add licenses, see Step 8: Complete post-migration tasks.
You can use either the Microsoft Azure Active Directory Synchronization Tool or the Microsoft Azure Active
Directory Sync Services (AAD Sync) to synchronize and create your on-premises users in Office 365. After
mailboxes are migrated to Office 365, you manage user accounts in your on-premises organization, and they're
synchronized with your Office 365 organization. For more information, seeDirectory Integration .
Step 2: Create a CSV file for a staged migration batch
After you identify the users whose on-premises mailboxes you want to migrate to Office 365, you use a comma
separated value (CSV ) file to create a migration batch. Each row in the CSV file—used by Office 365 to run the
migration—contains information about an on-premises mailbox.

NOTE
There isn't a limit for the number of mailboxes that you can migrate to Office 365 using a staged migration. The CSV file for a
migration batch can contain a maximum of 2,000 rows. To migrate more than 2,000 mailboxes, create additional CSV files
and use each file to create a new migration batch.

Supported attributes
The CSV file for a staged migration supports the following three attributes. Each row in the CSV file corresponds
to a mailbox and must contain a value for each of these attributes.

ATTRIBUTE DESCRIPTION REQUIRED?

EmailAddress Specifies the primary SMTP email Required


address, for example,
[email protected], for on-premises
mailboxes.
Use the primary SMTP address for on-
premises mailboxes and not user IDs
from the Office 365. For example, if the
on-premises domain is named
contoso.com but the Office 365 email
domain is named service.contoso.com,
you would use the contoso.com domain
name for email addresses in the CSV
file.

Password The password to be set for the new Optional


Office 365 mailbox. Any password
restrictions that are applied to your
Office 365 organization also apply to
the passwords included in the CSV file.

ForceChangePassword Specifies whether a user must change Optional


the password the first time they sign in
to their new Office 365 mailbox. Use
True or False for the value of this
parameter.
> [!NOTE]> If you've implemented a
single sign-on (SSO) solution by
deploying Active Directory Federation
Services (AD FS) or greater in your on-
premises organization, you must use
False for the value of the
ForceChangePassword attribute.

CSV file format


Here's an example of the format for the CSV file. In this example, three on-premises mailboxes are migrated to
Office 365.
The first row, or header row, of the CSV file lists the names of the attributes, or fields, specified in the rows that
follow. Each attribute name is separated by a comma.

EmailAddress,Password,ForceChangePassword
[email protected],Pa$$w0rd,False
[email protected],Pa$$w0rd,False
[email protected],Pa$$w0rd,False

Each row under the header row represents one user and supplies the information that will be used to migrate the
user's mailbox. The attribute values in each row must be in the same order as the attribute names in the header
row.
Use any text editor, or an application like Excel , to create the CSV file. Save the file as a .csv or .txt file.

NOTE
If the CSV file contains non-ASCII or special characters, save the CSV file with UTF-8 or other Unicode encoding. Depending
on the application, saving the CSV file with UTF-8 or other Unicode encoding can be easier when the system locale of the
computer matches the language used in the CSV file.

Step 3: Create a migration endpoint


To migrate email successfully, Office 365 needs to connect and communicate with the source email system. To do
this, Office 365 uses a migration endpoint. To create an Outlook Anywhere migration endpoint by using
PowerShell, for staged migration, first connect to Exchange Online.
For a full list of migration commands, see Move and migration cmdlets.
To create an Outlook Anywhere migration endpoint called "StagedEndpoint" in Exchange Online PowerShell, run
the following commands:

$Credentials = Get-Credential

New-MigrationEndpoint -ExchangeOutlookAnywhere -Name StagedEndpoint -Autodiscover -EmailAddress


[email protected] -Credentials $Credentials

For more information about the New-MigrationEndpoint cmdlet, seeNew -MigrationEndpoint.

NOTE
The New-MigrationEndpoint cmdlet can be used to specify a database for the service to use by using the -
TargetDatabase option. Otherwise a database is randomly assigned from the Active Directory Federation Services (AD FS)
2.0 site where the management mailbox is located.

Verify it worked
In Exchange Online PowerShell, run the following command to display information about the "StagedEndpoint"
migration endpoint:

Get-MigrationEndpoint StagedEndpoint | Format-List EndpointType,ExchangeServer,UseAutoDiscover,Max*

Step 4: Create and start a stage migration batch


You can use the New-MigrationBatch cmdlet in Exchange Online PowerShell to create a migration batch for a
cutover migration. You can create a migration batch and start it automatically by including the AutoStart
parameter. Alternatively, you can create the migration batch and then manually start it afterwards by using the
Start-MigrationBatch cmdlet. This example creates a migration batch called "StagedBatch1" and uses the
migration endpoint that was created in the previous step.

New-MigrationBatch -Name StagedBatch1 -SourceEndpoint StagedEndpoint -AutoStart

This example also creates a migration batch called "StagedBatch1" and uses the migration endpoint that was
created in the previous step. Because the AutoStart parameter isn't included, the migration batch has to be
manually started on the migration dashboard or by using Start-MigrationBatch cmdlet. As previously stated,
only one cutover migration batch can exist at a time.

New-MigrationBatch -Name StagedBatch1 -SourceEndpoint StagedEndpoint

Verify it worked
Run the following command in Exchange Online PowerShell to display information about the "StagedBatch1":

Get-MigrationBatch -Identity StagedBatch1 | Format-List

You can also verify that the batch has started by running the following command:

Get-MigrationBatch -Identity StagedBatch1 | Format-List Status

For more information about the Get-MigrationBatch cmdlet, seeGet-MigrationBatch.


Step 5: Convert on-premises mailboxes to mail-enabled users
After you have successfully migrated a batch of mailboxes, you need some way to let users get to their mail. A user
whose mailbox has been migrated now has both a mailbox on-premises and one in Office 365. Users who have a
mailbox in Office 365 will stop receiving new mail in their on-premises mailbox.
Because you are not done with your migrations, you are not yet ready to direct all users to Office 365 for their
email. So what do you do for those people who have both? What you can do is change the on-premises mailboxes
that you've already migrated to mail-enabled users. When you change from a mailbox to a mail-enabled user, you
can direct the user to Office 365 for their email instead of going to their on-premises mailbox.
Another important reason to convert on-premises mailboxes to mail-enabled users is to retain proxy addresses
from the Office 365 mailboxes by copying proxy addresses to the mail-enabled users. This lets you manage cloud-
based users from your on-premises organization by using Active Directory. Also, if you decide to decommission
your on-premises Exchange Server organization after all mailboxes are migrated to Office 365, the proxy
addresses you've copied to the mail-enabled users will remain in your on-premises Active Directory.
For more information, and to download scripts that you can run to convert mailboxes to mail-enabled users, see
the following:
Convert Exchange 2007 mailboxes to mail-enabled users
Convert Exchange 2003 mailboxes to mail-enabled users
Step 6: Delete a staged migration batch
After all mailboxes in a migration batch have been successfully migrated, and you've converted the on-premises
mailboxes in the batch to mail-enabled users, you're ready to delete a staged migration batch. Be sure to verify that
mail is being forwarded to the Office 365 mailboxes in the migration batch. When you delete a staged migration
batch, the migration service cleans up any records related to the migration batch and deletes the migration batch.
To delete the "StagedBatch1" migration batch in Exchange Online PowerShell, run the following command.

Remove-MigrationBatch -Identity StagedBatch1

For more information about the Remove-MigrationBatch cmdlet, seeRemove-MigrationBatch.


Verify it worked
Run the following command in Exchange Online PowerShell to display information about the "IMAPBatch1":

Get-MigrationBatch StagedBatch1

The command will return either the migration batch with a status of Removing, or it will return an error stating
that migration batch couldn't be found, verifying that the batch was deleted.
For more information about the Get-MigrationBatch cmdlet, seeGet-MigrationBatch.
Step7: Assign licenses to Office 365 users
Activate Office 365 user accounts for the migrated accounts by assigning licenses. If you don't assign a license, the
mailbox is disabled when the grace period (30 days) ends. To assign a license in the Office 365 admin center, see
Assign or unassign licenses for Office 365 for business.
Step 8: Complete post-migration tasks
Create an Autodiscover DNS record so users can easily get to their mailboxes. After all on-premises
mailboxes are migrated to Office 365, you can configure an Autodiscover DNS record for your Office 365
organization to enable users to easily connect to their new Office 365 mailboxes with Outlook and mobile
clients. This new Autodiscover DNS record has to use the same namespace that you're using for your Office
365 organization. For example, if your cloud-based namespace is cloud.contoso.com, the Autodiscover DNS
record you need to create is autodiscover.cloud.contoso.com.
Office 365 uses a CNAME record to implement the Autodiscover service for Outlook and mobile clients.
The Autodiscover CNAME record must contain the following information:
Alias: autodiscover
Target: autodiscover.outlook.com
For more information, see Create DNS records for Office 365 when you manage your DNS records.
Decommission on-premises Exchange servers. After you've verified that all email is being routed
directly to the Office 365 mailboxes, and you no longer need to maintain your on-premises email
organization or don't plan on implementing an SSO solution, you can uninstall Exchange from your servers
and remove your on-premises Exchange organization.
For more information, see the following:
Modify or Remove Exchange 2010
How to Remove an Exchange 2007 Organization
How to Uninstall Exchange Server 2003
Manage Office 365 with Windows PowerShell for
Delegated Access Permissions (DAP) partners
1/10/2018 • 1 min to read • Edit Online

Summary: Syndication and Cloud Solution Provider (CSP ) partners can use Windows PowerShell to manage
Office 365 customer tenants.
Delegated Access Permission (DAP ) partners are Syndication and Cloud Solution Providers (CSP ) Partners. They
are frequently network or telecom providers to other companies. They bundle Office 365 subscriptions into their
service offerings to their customers. When they sell an Office 365 subscription, they are automatically granted
Administer On Behalf Of (AOBO ) permissions to thecustomer tenancies so they can administer and report on the
customer tenancies. At best, this is difficult and time consuming to do in the Office 365 admin center. It is much
easier to do administrative tasks like listing all the customer TenantIds and their domains or identifying all users in
a customer tenancy and what licenses they are assigned by using Windows PowerShell for Office 365. In some
cases, it is possible to do these administrative tasks only in Windows PowerShell for Office 365. Here are samples
of scenarios that Syndication and CSP partners most frequently use to administer their customer tenancies:

Manage Office 365 tenants with Windows PowerShell for Delegated Access Permissions (DAP ) partners
Add a domain to a client tenancy with Windows PowerShell for Delegated Access Permission (DAP )
partners
Connect to Exchange Online tenants with remote Windows PowerShell for Delegated Access Permissions
(DAP ) partners
Retrieve customer tenant reporting data with Windows PowerShell for Delegated Access Permissions (DAP )
partners
Aggregate customer reporting data via Windows PowerShell for Delegated Access Permission (DAP )
partners
Manage Office 365 tenants with Windows PowerShell
for Delegated Access Permissions (DAP) partners
4/19/2018 • 3 min to read • Edit Online

Summary: Use Windows PowerShell for Office 365 to manage your customer tenancies.
Windows PowerShell allows Syndication and Cloud Solution Provider (CSP ) partners to easily administer and
report on customer tenancy settings that are not available in the Office 365 admin center. Note that Administer on
Behalf Of (AOBO ) permissions are required for the partner administrator account to connect to its customer
tenancies.
Delegated Access Permission (DAP ) partners are Syndication and Cloud Solution Providers (CSP ) Partners. They
are frequently network or telecom providers to other companies. They bundle Office 365 subscriptions into their
service offerings to their customers. When they sell an Office 365 subscription, they are automatically granted
Administer On Behalf Of (AOBO ) permissions to thecustomer tenancies so they can administer and report on the
customer tenancies.

What do you need to know before you begin?


The procedures in this topic require you to connect to Windows PowerShell for Office 365. For instructions, see
Connect to Office 365 PowerShell.
You also need your partner tenant administrator credentials.

What do you want to do?


List all tenant IDs

NOTE
If you have more than 500 tenants, scope the cmdlet syntax with either -All or -MaxResultsParameter. This applies to other
cmdlets that can give a large output, such as Get-MsolUser.

To list all customer tenant Ids that you have access to, run this command.

Get-MsolPartnerContract -All | Select-Object -TenantId

This will display a listing of all your customer tenants by TenantId.


Get a tenant ID by using the domain name
To get the TenantId for a specific customer tenant by domain name, run this command. Replace
<domainname.onmicrosoft.com> with the actual domain name of the customer tenant that you want.

Get-MsolPartnerContract -DomainName <domainname.onmicrosoft.com> | Select-Object -TenantId

List all domains for a tenant


To get all domains for any one customer tenant, run this command. Replace with the actual value.
Get-MsolDomain -TenantId <customer TenantId value>

If you have registered additional domains, this will return all domains associated with the customer TenantId.
Get a mapping of all tenants and registered domains
The previous Windows PowerShell for Office 365 commands showed you how to retrieve either tenant IDs or
domains but not both at the same time, and with no clear mapping between them all. This command generates a
listing of all your customer tenant IDs and their domains.

$Tenants = Get-MsolPartnerContract -All; $Tenants | foreach {$Domains = $_.TenantId; Get-MsolDomain -TenantId


$Domains | fl @{Label="TenantId";Expression={$Domains}},name}

Get all users for a tenant


This will display the UserPrincipalName, the DisplayName, and the isLicensed status for all users for a
particular tenant. Replace with the actual value.

Get-MsolUser -TenantID <customer TenantId value>

Get all details about a user


If you want to see all the properties of a particular user, run this command. Replace and with the actual values.

Get-MsolUser -TenantId <customer TenantId value> -UserPrincipalName <user principal name value>

Add users, set options, and assign licenses


The bulk creation, configuration, and licensing of Office 365 users is particularly efficient by using Windows
PowerShell for Office 365. In this two-step process, you first create entries for all the users you want to add in a
comma-separated value (CSV ) file and then import that file by using Windows PowerShell for Office 365.
Create a CSV file
Create a CSV file by using this format:
UserPrincipalName,FirstName,LastName,DisplayName,Password,TenantId,UsageLocation,LicenseAssignment

where:
UsageLocation: The value for this is the two-letter ISO country/region code of the user. The
country/region codes can be looked up at theISO Online Browsing Platform. For example, the code for the
United States is US, and the code for Brazil is BR.
LicenseAssignment: The value for this uses this format: syndication-account:<PROVISIONING_ID> . For
example, if you are assigning customer tenant users O365_Business_Premium licenses, the
LicenseAssignment value looks like this: syndication-account:O365_Business_Premium. You will find
the PROVISIONING_IDs in the Syndication Partner Portal that you have access to as a Syndication or CSP
partner.
Import the CSV file and create the users
After you have your CSV file created, run this command to create user accounts with non-expiring passwords that
the user must change at first sign-in and that assigns the license you specify. Be sure to substitute the correct CSV
file name.
Import-Csv .\FILENAME.CSV | foreach {New-MsolUser -UserPrincipalName $_.UserPrincipalName -DisplayName
$_.DisplayName -FirstName $_.FirstName -LastName $_.LastName -Password $_.Password -UsageLocation
$_.UsageLocation -LicenseAssignment $_.LicenseAssignment -ForceChangePassword:$true -
PasswordNeverExpires:$true -TenantId $_.TenantId}

See also
Help for partners
Add a domain to a client tenancy with Windows
PowerShell for Delegated Access Permission (DAP)
partners
1/10/2018 • 3 min to read • Edit Online

Summary: Use Windows PowerShell for Office 365 to add an alternate domain name to an existing customer
tenant.
You can create and associate new domains with your customer's tenancy with Windows PowerShell for Office 365
faster than using the Office 365 admin center.
Delegated Access Permission (DAP ) partners are Syndication and Cloud Solution Providers (CSP ) Partners. They
are frequently network or telecom providers to other companies. They bundle Office 365 subscriptions into their
service offerings to their customers. When they sell an Office 365 subscription, they are automatically granted
Administer On Behalf Of (AOBO ) permissions to thecustomer tenancies so they can administer and report on the
customer tenancies.

What do you need to know before you begin?


UNRESOLVED_TOKEN_VAL (GENL_O365_PowerShell_BeforeYouBegin)
You also need the following information:
You need the fully qualified domain name (FQDN ) that your customer wants.
You need the customer's TenantId.
The FQDN must be registered with an Internet domain name service (DNS ) registrar, such as GoDaddy. For
more information on how to publically register a domain name, see How to buy a domain name.
You need to know how to add a TXT record to the registered DNS zone for your DNS registrar. For more
information on how to add a TXT record, see Create DNS records at any DNS hosting provider for Office
365. If those procedures don't work for you, you will need to find the procedures for your DNS registrar.

Create domains
Your customers will likely ask you to create additional domains to associate with their tenancy because they don't
want the default .onmicrosoft.com domain to be the primary one that represents their corporate identities to the
world. This procedure walks you through creating a new domain associated with your customer's tenancy.

NOTE
To perform some of these operations, the partner administrator account you sign in with must be set to Full administration
for the Assign administrative access to companies you support setting found in the details of the admin account in the
Office 365 admin center. For more information on managing partner administrator roles, seePartners: Offer delegated
administration.

Create the domain in Azure Active Directory


This command creates the domain in Azure Active Directory but does not associate it with the publically registered
domain. That comes when you prove that you own the publically registered domain to Microsoft Office 365 for
enterprises.

New-MsolDomain -TenantId <customer TenantId> -Name <FQDN of new domain>

Get the data for the DNS TXT verification record


Office 365 will generate the specific data that you need to place into the DNS TXT verification record. To get the
data, run this command.

Get-MsolDomainVerificationDNS -TenantId <customer TenantId> -DomainName <FQDN of new domain>

This will give you output like:


Label: domainname.com

Text: MS=ms########

Ttl: 3600

NOTE
You will need this text to create the TXT record in the publically registered DNS zone. Be sure to copy and save it.

Add a TXT record to the publically registered DNS zone


Before Office 365 will start accepting traffic that is directed to the publically registered domain name, you must
prove that you own and have administrator permissions to the domain. You prove you own the domain by creating
a TXT record in the domain. A TXT record doesn't do anything in your domain, and it can be deleted after your
ownership of the domain is established. To create the TXT records, follow the procedures at Create DNS records at
any DNS hosting provider for Office 365. If those procedures don't work for you , you need to find the procedures
for your DNS registrar.
Confirm the successful creation of the TXT record via nslookup. Follow this syntax.

nslookup -type=TXT <FQDN of registered domain>

This will give you output like:


Non-authoritative answer:

FQDN of the registered domain

text=MS=ms########

Validate domain ownership in Office 365


In this last step, you validate to Office 365 that you own the publically registered domain. After this step, Office
365 will begin accepting traffic routed to the new domain name. To complete the domain creation and registration
process, run this command.

Confirm-MsolDomain -TenantId <customer TenantId> -DomainName <FQDN of new domain>

This command won't return any output, so to confirm that this worked, run this command.

Get-MsolDomain -TenantId <customer TenantId> -DomainName <FQDN of new domain>


This will return something like this

Name Status Authentication

FQDN of new domain Verified Managed

See also
Help for partners
Connect to Exchange Online tenants with remote
Windows PowerShell for Delegated Access
Permissions (DAP) partners
5/25/2018 • 4 min to read • Edit Online

Summary: Use remote Windows PowerShell to connect to Exchange Online by using the DelegatedOrg
parameter.
Remote Windows PowerShell lets you manage your Exchange Online settings from the command line. You use
Windows PowerShell on your local computer to create a remote session to Exchange Online. It's a three-step
process where you enter your Exchange Online credentials, provide the required connection settings, and then
import the Exchange Online cmdlets into your local Windows PowerShell session so that you can use them.

What do you need to know before you begin?


Estimated time to complete: 5 minutes
You can use the following versions of Windows:
Windows 10
Windows 8.1 or Windows 8
Windows Server 2012 R2 or Windows Server 2012
Windows 7 Service Pack 1 (SP1)*
Windows Server 2008 R2 SP1*
* You need to install the .NET Framework 4.5.1 or the .NET Framework 4.5 and then either the
Windows Management Framework 4.0 or the Windows Management Framework 3.0 . For more
information, see the following resources:
Installing the .NET Framework
Windows Management Framework 3.0 or Windows Management Framework 4.0
For information about keyboard shortcuts that might apply to the procedures in this topic, see Keyboard
shortcuts in the Exchange admin center.

IMPORTANT
This procedure is only for Delegated Access Permission (DAP) partners. If you are not a DAP partner, do not use this
procedure.

DAP partners are Syndication and Cloud Solution Providers (CSP ) partners. They are frequently network or
telecom providers to other companies. They bundle subscriptions into their service offerings to their customers.
They own a partner tenancy that is automatically granted Administer On Behalf Of (AOBO ) permissions to their
Office 365customer tenancies so they can administer and report on all of their customer tenancies.

Connect to Exchange Online


1. On your local computer, open Windows PowerShell and run the following command.

$UserCredential = Get-Credential

In the Windows PowerShell Credential Request dialog box, enter your DAP administrator user name
and password, and then click OK.
2. Run the following command, replacing with the name of the tenant domain that you want to connect to.

$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri


https://ps.outlook.com/powershell-liveid?DelegatedOrg=<customer tenant domain name> -Credential
$UserCredential -Authentication Basic -AllowRedirection

The key step in this command is specifying which customer to access for the reporting information. You do
this in the ConnectionURI parameter, where you provide the FQDN of the initial domain name as the value
to the DelegatedOrg parameter. This tells remote Windows PowerShell for Exchange Online PowerShell
remote Windows PowerShell the endpoint to connect to. remote Windows PowerShell must connect to
Office 365 reporting in the context of a specific customer each time a report is run. After this customer is
specified, all of the following commands are run in the context of that customer. This lets the partner to
access all the available reports for this customer.
3. Run the following command.

Import-PSSession $Session

NOTE
There is a limit of three simultaneous sessions that can run under one account. Be sure to disconnect the remote Windows
PowerShell session when you're finished. If you close the Windows PowerShell window without disconnecting the session, you
can use up all the remote Windows PowerShell sessions available to you, and you'll need to wait for the sessions to expire. To
disconnect the remote Windows PowerShell session, run the following command. > Remove-PSSession $Session

How do you know this worked?


After Step 3, the Exchange Online cmdlets are imported into your local Windows PowerShell session as tracked by
a progress bar. If you don't receive any errors, you connected successfully. A quick test is to run an Exchange
Online cmdlet—for example, Get-Mailbox —and see the results.
If you receive errors, check the following requirements:
A common problem is an incorrect password. Run the three steps again and pay close attention to the user
name and password you enter in Step 1.
To help prevent denial-of-service (DoS ) attacks, you're limited to three open remote Windows PowerShell
connections to your Exchange Online organization.
Windows PowerShell needs to be configured to run scripts. You need to configure this setting only once on
your computer, not every time you connect. To enable Windows PowerShell to run signed scripts, run the
following command in an elevated Windows PowerShell window (a Windows PowerShell window you
opened by selecting Run as administrator).

Set-ExecutionPolicy RemoteSigned
The account you use to connect to Exchange Online must be enabled for remote Windows PowerShell. For
more information, see Manage Remote PowerShell Access in Exchange Online.
TCP port 80 traffic needs to be open between your local computer and Exchange Online. It's probably open,
but it's something to consider if your organization has a restrictive Internet access policy.

Call the cmdlet directly with Invoke-Command


Importing a remote Windows PowerShell session can be a lengthy process because it brings in all Exchange
Online cmdlets. This can be an issue in batch processing—for example, when you are running reports or making
bulk changes for different tenants. As an alternative to using Import-PSSession, you can call cmdlets you want to
use directly with Invoke-Command. For example, to call the get-mailbox cmdlet, substitute this syntax for
Import-PSSession $Session .

Invoke-Command -Session $Session -ScriptBlock {Get-Mailbox}

More reporting cmdlets


The cmdlets that you used in this topic are Windows PowerShell cmdlets. For more information about these
cmdlets, see the following topics:
Get-Credential
New -PSSession
Import-PSSession
Remove-PSSession
Set-ExecutionPolicy
Retrieve customer tenant reporting data with
Windows PowerShell for Delegated Access
Permissions (DAP) partners
1/10/2018 • 1 min to read • Edit Online

Summary: Use remoteWindows PowerShell for Microsoft Exchange Online to retrieve reports from individual
customer tenants.
Syndication and Cloud Solution Provider (CSP ) partners can access the data that makes up customer tenant
reports directly via remoteWindows PowerShell for Exchange Online PowerShell. This lets partners collect and
save the reporting data and then perform other operations on it. After you open a remote connection, retrieving
reporting data about a customer tenancy is identical to running any cmdlet against a customer tenancy.
In this article, you use remoteWindows PowerShell for Exchange Online to connect to a single customer tenancy
and retrieve a report. By default, Windows PowerShell does not support aggregating reporting data from multiple
customer tenancies. The reports you retrieve with this procedure are only for the DelegatedOrg that you connect
to.
If you want to retrieve a single report for all your customer tenancies, a sample script to do this can be found in
Aggregate customer reporting data via Windows PowerShell for Delegated Access Permission (DAP ) partners .

Before you begin


You need to connect to your Exchange Online tenant by using remote Windows PowerShell. For instructions,
see Connect to Exchange Online tenants with remote Windows PowerShell for Delegated Access Permissions
(DAP ) partners

Run the Get-StaleMailboxReport sample


After you have opened a remote session to Exchange Online, run this command to retrieve the Get-
StaleMailboxReport for the date range 03/25/2015 through 03/31/2015.

Get-StaleMailboxReport -StartDate 03/25/2015 -EndDate 03/31/2015

There are many other reporting cmdlets available for Exchange Online, Lync Online, and SharePoint Online as well
as others for message tracing that you can use. To find out more about the available reporting cmdlets and the
Office 365 Reporting web service, see the topics in the following section.

See also
Office 365 Reporting web service
Reporting cmdlets in Exchange Online
Help for partners
Aggregate customer reporting data via Windows
PowerShell for Delegated Access Permission (DAP)
partners
4/19/2018 • 3 min to read • Edit Online

Summary: Use Windows PowerShell for Office 365 to retrieve reports on all customer tenancies and aggregate
the data into a single location.
By default, Windows PowerShell for Office 365 does not have a built-in aggregation of reporting data from
multiple customer tenancies. However, you can use this sample Windows PowerShell for Office 365 script to
iterate through all your customer tenancies to retrieve a single report for each of your customers and then
aggregate the reporting data into a single location. The result is that you'll have a single report for all your
customer tenants.
Delegated Access Permission (DAP ) partners are Syndication and Cloud Solution Providers (CSP ) Partners. They
are frequently network or telecom providers to other companies. They bundle Office 365 subscriptions into their
service offerings to their customers. When they sell an Office 365 subscription, they are automatically granted
Administer On Behalf Of (AOBO ) permissions to thecustomer tenancies so they can administer and report on the
customer tenancies.

Before you begin


To use this script, substitute your particular values in for these variables:
$UserName - This is your partner administrator user name. These credentials will be used to connect to all
your customer tenancies.
$OutputFile - This is the comma-separated value file that reporting data will be aggregated to.
$ErrorFile - This is the text log file for errors.
$ScriptBlock - This sample script uses Get-MailboxActivityReport and parameters (such as start and
end dates) so you have a way to get started. If you want other reports, substitute the report name that you
want and necessary parameters for Get-MailboxActivityReport.
Open a remote Windows PowerShell session to Exchange Online by using the steps in Connect to
Exchange Online tenants with remote Windows PowerShell for Delegated Access Permissions (DAP )
partners

Use Windows PowerShell to aggregate customer tenant reports to a


single location
1. Copy and paste this script into Notepad.

# Import the MSOnline module to allow connectivity to Office 365.

Import-Module MSOnline

This is the partner admin user name to be used to run the


report.
$UserName = "[email protected]"

These are the locations for the report output and error log.
$OutputFile = ".\ReportOutput.csv"
$ErrorFile = ".\Errors.txt"

This is the report to run and all the necessary parameters.


$ScriptBlock = {Get-MailboxActivityReport -ReportType Daily -StartDate 03/18/2015 -EndDate 03/18/2015}
$LinesToSkip = 0

This is the prompt for the password of the partner admin


user name.
$Cred = get-credential -Credential $UserName

Establish a Windows PowerShell session with Office 365.


Connect-MsolService -Credential $Cred

Get all the contracts for the signed-in partner.


Contracts define the AOBO/DAP relationship between the
partner and the customers.
$Contracts = Get-MsolPartnerContract -All
Write-Host "Found $($Contracts.Count) customers for this Partner."

For each of the contracts (customers), run the specified


report and output the information.
foreach ($c in $contracts) {
# Get the initial domain for the customer.

$InitialDomain = Get-MsolDomain -TenantId $c.TenantId | Where {$_.IsInitial -eq $true}

# Construct the URL with the DelegatedOrg parameter.

$DelegatedOrgURL = "https://ps.outlook.com/powershell-liveid?DelegatedOrg=" + $InitialDomain.Name

Write-Host "Running report for $($InitialDomain.Name)"

# Invoke-Command establishes a Windows PowerShell session based on the URL,


# runs the command, and closes the Windows PowerShell session.

$ReportInfo = Invoke-Command -ConnectionUri $DelegatedOrgURL -Credential $Cred -Authentication Basic -


ConfigurationName Microsoft.Exchange -AllowRedirection -ScriptBlock $ScriptBlock -HideComputerName

# If Invoke-Command returned information (that is, it's not NULL), format and output the information.

If ($ReportInfo) {

Write-Host "Writing report information for $($InitialDomain.Name) to $OutputFile" -foregroundcolor green

# Convert the report data to CSV format.


# For the first time, don't skip any lines, so include the header.
# For all other times, skip the first line (so don't rewrite the header).

$OutputInfo = $ReportInfo | ConvertTo-CSV -NoTypeInformation | Select -Skip $LinesToSkip

Out-File $OutputFile -InputObject $OutputInfo -Append

$LinesToSkip = 1

} else {

# If Invoke-Command didn't return and report data, log an error.

Write-Host "No report information for $($InitialDomain.Name)." -foregroundcolor yellow

Out-File $ErrorFile -InputObject @("No report information for $($InitialDomain.Name).") -Append


}

2. Save the script as GetMailboxActivityReport.ps1 in a location that's easy for you to find. For the example,
the file is saved in C:\\O365 Scripts.

3. Run the script in remote Windows PowerShell by following this syntax.

& "C:\O365 Scripts\GetMailboxActivityReport.ps1"

This sample script places the aggregated report in the ReportOutput.csv file.

## See also

####

[Help for partners](https://go.microsoft.com/fwlink/p/?LinkID=533477)

[Office 365 Reporting web service](https://go.microsoft.com/fwlink/p/?LinkId=532777)

[Reporting cmdlets in Exchange Online](https://go.microsoft.com/fwlink/p/?LinkId=526430)


Manage Skype for Business Online with Office 365
PowerShell
5/22/2018 • 1 min to read • Edit Online

Summary: Use Office 365 PowerShell to manage Skype for Business Online policies, per-user policies, and
meeting settings.
One of the primary tasks of any Skype for Business Online administrator is managing policies. Although you can
accomplish some of these tasks in the Office 365 Admin center, other tasks are much quicker and easier in Office
365 PowerShell.

Before you start


Download and install the Skype for Business Online Connector module, and then restart your computer if
prompted.

Connect using a Skype for Business Online administrator account


name and password
1. Open a Windows PowerShell command prompt and run the following commands:

Import-Module LyncOnlineConnector
$userCredential = Get-Credential
$sfbSession = New-CsOnlineSession -Credential $userCredential
Import-PSSession $sfbSession

2. In the Windows PowerShell Credential Request dialog box, type your Skype for Business Online
administrator account name and password, and then click OK.

Connect using a Skype for Business Online administrator account with


multifactor authentication
1. Open a Windows PowerShell command prompt and run the following commands:

Import-Module LyncOnlineConnector
$sfbSession = New-CsOnlineSession
Import-PSSession $sfbSession

2. When prompted by the New-CsOnlineSession command, enter your Skype for Business Online
administrator account name.
3. In the Sign in to your account dialog box, type your Skype for Business Online administrator password,
and then click Sign in.
4. Follow the instructions in the Sign in to your account dialog box to provide additional authentication
information, such as a verification code, and then click Verify.
For more information, see the following topics:
Manage Skype for Business Online policies with Office 365 PowerShell
Assign per-user Skype for Business Online policies with Office 365 PowerShell

See also
Manage Office 365 with Office 365 PowerShell
Getting started with Office 365 PowerShell
Manage Skype for Business Online policies with
Office 365 PowerShell
1/10/2018 • 3 min to read • Edit Online

Summary: Use Office 365 PowerShell to manage your Skype for Business Online user account properties with
policies.
To manage many properties of user account for Skype for Business Online, you must specify them as properties of
policies with Office 365 PowerShell.

Before you begin


Use these instructions to get set up to run the commands (skip the steps you have already completed):
1. Download and install the Skype for Business Online Connector module.
2. Open a Windows PowerShell command prompt and run the following commands:

Import-Module LyncOnlineConnector
$userCredential = Get-Credential
$sfbSession = New-CsOnlineSession -Credential $userCredential
Import-PSSession $sfbSession

When prompted, enter your Skype for Business Online administrator account name and password.

Manage user account policies


Many Skype for Business Online user account properties are configured by using policies. Policies are simply
collections of settings that can be applied to one or more users. To take a look at how the a policy has been
configured, you can run this example command for the FederationAndPICDefault policy:

Get-CsExternalAccessPolicy -Identity "FederationAndPICDefault"

In turn, you should get back something similar to this:

Identity : Tag:FederationAndPICDefault
Description :
EnableFederationAccess : True
EnableXmppAccess : False
EnablePublicCloudAccess : True
EnablePublicCloudAudioVideoAccess : True
EnableOutsideAccess : True

In this example, the values within this policy determine what a use can or cannot do when it comes to
communicating with federated users. For example, the EnableOutsideAccess property must be set to True for a
user to be able to communicate with people outside the organization. Note that this property does not appear in
the Office 365 Admin center. Instead, the property is automatically set to True or False based on the other
selections that you make. The other two properties of interest are:
EnableFederationAccess indicates whether the user can communicate with people from federated
domains.
EnablePublicCloudAccess indicates whether the user can communicate with Windows Live users.
Therefore, you don't directly change federation-related properties on user accounts (for example, Set-CsUser -
EnableFederationAccess $True). Instead, you assign an account an external access policy that has the desired
property values preconfigured. If we want a user to be able to communicate with federated users and with
Windows Live users, that user account must be assigned a policy that allows those types of communication.
If you want to know whether or not someone can communicate with users from outside the organization, you have
to:
Determine which external access policy has been assigned to that user.
Determine which capabilities are or are not allowed by that policy.
For example, you can do that by using this command:

Get-CsOnlineUser -Identity "Alex Darrow" | ForEach {Get-CsExternalAccessPolicy -Identity


$_.ExternalAccessPolicy}

This command finds the policy assigned to the user, then finds the capabilities enabled or disabled within that
policy.
Note that there are no cmdlets for creating or for modifying policies. You must use the policies pre-supplied by
Office 365. If you want to take a look at the different policies available, you can use these commands:
Get-CsClientPolicy
Get-CsConferencingPolicy
Get-CsDialPlan
Get-CsExternalAccessPolicy
Get-CsHostedVoicemailPolicy
Get-CsPresencePolicy
Get-CsVoicePolicy

NOTE
A Skype for Business Online dial plan is a policy in every respect except the name. The name "dial plan" was chosen instead of,
say, "dialing policy" in order to provide backward compatibility with Office Communications Server and with Exchange.

For example, to look at all the voice policies available for your use, run this command:

Get-CsVoicePolicy

NOTE
That returns a list of all the voice policies available to you. Keep in mind, however, that not all policies can be assigned to all
users. This is due to various restrictions involving licensing and geographic location. (The so-called "usage location.") If you
want to know the external access policies and the conferencing policies that can be assigned to a particular user, use
commands similar to these:

Get-CsConferencingPolicy -ApplicableTo "Alex Darrow"


Get-CsExternalAccessPolicy -ApplicableTo "Alex Darrow"
The ApplicableTo parameter limits the returned data to policies that can be assigned to the specified user (for
example, Alex Darrow ). Depending on licensing and usage location restrictions, that might represent a subset of all
the available policies.
In some cases, properties of policies are not used with Office 365, while others can only be managed by Microsoft
support personnel.
With Skype for Business Online, users must be managed by a policy of some kind. If a valid policy-related
property is blank, that means that the user in question is being managed by a global policy, which is a policy that is
automatically applied to a user unless he or she is specifically assigned a per-user policy. Because we don't see a
client policy listed for a user account, it is managed by the global policy. You can determine the global client policy
with this command:

Get-CsClientPolicy -Identity "Global"

See also
Manage Skype for Business Online with Office 365 PowerShell
Manage Office 365 with Office 365 PowerShell
Getting started with Office 365 PowerShell
Assign per-user Skype for Business Online policies
with Office 365 PowerShell
1/10/2018 • 4 min to read • Edit Online

Summary: Use Office 365 PowerShell to assign per-user communication settings with Skype for Business Online
policies.
Using Office 365 PowerShell is an efficient way to assign per-user communication settings with Skype for
Business Online policies.

Before you begin


Use these instructions to get set up to run the commands (skip the steps you have already completed):
1. Download and install the Skype for Business Online Connector module.
2. Open a Windows PowerShell command prompt and run the following commands:

Import-Module LyncOnlineConnector
$userCredential = Get-Credential
$sfbSession = New-CsOnlineSession -Credential $userCredential
Import-PSSession $sfbSession

When prompted, enter your Skype for Business Online administrator account name and password.

Updating external communication settings for a user account


Suppose you want to change external communication settings on a user account. For example, you want to allow
Alex to communicate with federated users (EnableFederationAccess is equal to True) but not with Windows Live
users (EnablePublicCloudAccess equals False). To do that, you need to do two things:
1. Find an external access policy that meets our criteria.
2. Assign that external access policy to Alex.

NOTE
You can't create a custom policy all our own. That's because Skype for Business Online does not allow you to create custom
policies. Instead, you must assign one of the policies that were created specifically for Office 365. Those pre-created policies
include: 4 different client policies, 224 different conferencing policies, 5 different dial plans, 5 different external access policies,
1 hosted voicemail policy, and 4 different voice policies.

So how do you determine which external access policy to assign Alex? The following command returns all the
external access policies where EnableFederationAccess is set to True and EnablePublicCloudAccess is set to False:

Get-CsExternalAccessPolicy | Where-Object {$_.EnableFederationAccess -eq $True -and $_.EnablePublicCloudAccess


-eq $False}

What the command does is return all the policies that meet two criteria: the EnableFederationAccess property is
set to True, and the EnablePublicCloudAccess policy is set to False. In turn, that command returns one policy that
meets our criteria (FederationOnly). Here is an example:

Identity : Tag:FederationOnly
Description :
EnableFederationAccess : True
EnableXmppAccess : False
EnablePublicCloudAccess : False
EnablePublicCloudAudioVideoAccess : False
EnableOutsideAccess : True

NOTE
The policy Identity says Tag:FederationOnly. As it turns out, the Tag: prefix is a carryover from the early pre-release work done
on Microsoft Lync 2013. When it comes to assigning policies to users, you should delete the Tag: prefix and use just the
policy name: FederationOnly.

Now that you know which policy to assign to Alex, we can assign that policy by using the Grant-
CsExternalAccessPolicy cmdlet. Here is an example:

Grant-CsExternalAccessPolicy -Identity "Alex Darrow" -PolicyName "FederationOnly"

Assigning a policy is pretty simple: you simply specify the Identity of the user and the name of the policy to be
assigned.
And when it comes to policies and policy assignments, you're not limited to working with user accounts one a time.
For example, suppose you need a list of all the users who are allowed to communicate with federated partners and
with Windows Live users. We already know that those users have been assigned the external user access policy
FederationAndPICDefault. Because we know that, you can display a list of all those users by running one simple
command. Here is the command:

Get-CsOnlineUser -Filter {ExternalAccessPolicy -eq "FederationAndPICDefault"} | Select-Object DisplayName

In other words, show us all the users where the ExternalAccessPolicy property is set to FederationAndPICDefault.
(And, in order to limit the amount of information that appears onscreen, use the Select-Object cmdlet to display
show us only each user's display name.)
To configure all our user accounts to use that same policy, use this command:

Get-CsOnlineUser | Grant-CsExternalAccessPolicy "FederationAndPICDefault"

This command uses Get-CsOnlineUser to return a collection of all the users who have been enabled for Lync, then
sends all that information to Grant-CsExternalAccessPolicy, which assigns the FederationAndPICDefault policy to
each and every user in the collection.
As an additional example, suppose you've previously assigned Alex the FederationAndPICDefault policy and now
you've changed your mind and would like him to be managed by the global external access policy. You can't
explicitly assign the global policy to anyone. It is only used if no other per-user policy is assigned. Therefore, if we
want Alex to be managed by the global policy, you need to unassign any per-user policy previously assigned to
him. Here is an example command:

Grant-CsExternalAccessPolicy -Identity "Alex Darrow" -PolicyName $Null


This command sets the name of the external access policy assigned to Alex to a null value ($Null). Null means
"nothing". In other words, no external access policy is assigned to Alex. When no external access policy is assigned
to a user, that user then gets managed by the global policy.
To disable a user account using Windows PowerShell, use the Azure Active Directory cmdlets to remove Alex's
Skype for Business Online license. For more information, see Disable access to services with Office 365
PowerShell.

See also
Manage Skype for Business Online with Office 365 PowerShell
Manage Office 365 with Office 365 PowerShell
Getting started with Office 365 PowerShell

You might also like