Live Cyber Attack Lab 🎯 Watch our IR team detect & respond to a rogue insider trying to steal data! Choose a Session

X

13 Must-Know Office 365 PowerShell Commands

PowerShell

image of a monitor with files on it

Using PowerShell to manage Office 365 can make your work faster, more efficient, and easier. PowerShell gives you access to information about your Office 365 environment that you can’t access through the Microsoft 365 admin center, and allows you to carry out bulk operations using a single command. By integrating your Office 365 products into a single interface, PowerShell also makes it easier to manage user access and improve cybersecurity.

This article will explain the most useful Office 365 PowerShell commands for system administrators. We’ve broken these commands into three categories – automation, reporting, and configuration – so you can quickly find what you need.

Get the Free PowerShell and Active Directory Essentials Video Course

I'd recommend this for both new and advanced PowerShell users. Building an AD tool is a great learning experience.

Our free video course on hidden Office 365 settings you can unlock with PowerShell will show you more commands for using PowerShell with Office 365.

Ways to Leverage Office 365 with PowerShell

Ways to leverage PowerShell commands

The Microsoft 365 Admin Center is great for basic users. Using this system, you can manage your Office 365 user accounts and licenses, as well as services like Exchange Online, Teams, and SharePoint Online.

You can also manage all of these aspects of your Office 365 setup with Office 365 PowerShell. This gives you the power of a command-line interface and the ability to write scripts. This makes automation much easier and makes your work more efficient.

More specifically, there are a few key ways in which Office 365 PowerShell helps you to manage Office 365 more easily:

  • Office 365 PowerShell will reveal additional information that you cannot see with the Microsoft 365 admin center.
  • PowerShell lets you configure features and settings not available through the Office 365 Admin Center.
  • If you are using Office 365 for file-sharing, Office 365 PowerShell allows you to quickly audit and manage user access to shared drives.
  • Because Office 365 PowerShell is a command-line tool, you can easily perform bulk operations.
  • You can use the cmdlets in Office 365 PowerShell to filter data pulled from your Office 365 system, giving you quick access to information on users and systems.
  • Office 365 PowerShell can also be used to automate the process of collecting data from your system, and to output this into a CSV file.
  • Because of its ability to quickly audit user information, Office 365 PowerShell is a powerful way to monitor and improve your cybersecurity.
  • Finally, because Office 365 PowerShell is designed to work across all Office 365 components, you can use it to gather information from the various discrete parts of the system.

All of these functions are extremely useful for system administrators. However, it should also be noted that Office 365 PowerShell is designed to augment and enhance your ability to manage Office 365, not to replace the Microsoft 365 admin center. There are some tasks that will remain more efficient through the Admin Center, just as there are some configuration procedures that can only be done with Office 365 PowerShell commands.

On the other hand, once you’ve learned the basics of PowerShell, the system is almost infinitely expandable. There are dozens of PowerShell tools that can make system administration even easier and more rapid, and getting used to the command line means that you can use scripts to automate frequent (and time-consuming) tasks.

Finally, try out the PowerShell Integrated Scripting Environment (ISE) for all your PowerShell needs. Of course, it makes PowerShell scripting easier, but it also makes for a better CLI experience.

Office 365 PowerShell Commands for Automation

PowerShell Command tip for automation

One of the most compelling reasons to use Office 365 PowerShell is that it allows you to automate many common tasks and processes. Automation can make your workflow more efficient, and can also reduce the risk of human error in system administration.

Instead of manually working through dozens of user accounts, you can use Office 365 PowerShell to quickly collect, filter, and organize information on users. You can then use the same command-line interface to apply bulk actions to the same account.

Here are the most useful Office 365 PowerShell commands for automation:

1. Connecting To An Office 365 Instance with Office 365 PowerShell

Before starting to use Office 365 PowerShell, you will need to download and install the Office 365 module for Windows PowerShell, and connect it to your Office 365 instance. Here’s how to do that:

Install-Module -Name AzureAD

Install-Module -Name MSOnline
  • Enter your Office 365 admin credentials:
$Cred = Get-Credential
  • Now you need to create a PowerShell session as a remote user. You can do that using the following command:
$O365 = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $Cred -Authentication Basic -AllowRedirection
  • Now, import the session commands into the local Windows PowerShell session:
Import-PSSession $O365
  • Finally, connect your session to all of your Office 365 services using this command:
Connect-MsolService –Credential $O365

This will connect Office 365 PowerShell to your Office 365 instance, and let you manage it using Office 365 PowerShell.

2. Connecting To Exchange Online and SharePoint Online with PowerShell

You may also want to connect to Microsoft Exchange Online and Microsoft SharePoint Online, in order to manage these services from the same PowerShell instance. We’ve written a detailed guide on how to do this in our article on Connecting Office 365 with PowerShell, but here are the details for reference:

  • Connecting to Exchange Online is essentially the same process as connecting to Office 365. Here are the relevant commands:
$Cred = Get-Credential

$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $Cred -Authentication Basic –AllowRedirection
  • Connecting to SharePoint Online is a little more complicated, and you will need to install further software:
  • First, install the SharePoint Online Management Shell feature.
  • Then run the following command from PowerShell:
$admin="Admin@enterprise.onmicrosoft.com"

$orgname="enterprise"

$userCred = Get-Credential -UserName $admin -Message "Type the password."

Connect-SPOService -Url https://$orgname-admin.sharepoint.com -Credential $userCred

You can then use manage both SharePoint Online and Microsoft Exchange Online from PowerShell.

3. Get a list of available Office 365 PowerShell cmdlets

Cmdlets are the primary type of command for Office 365 PowerShell, and are the tools that you will be using most often. Office 365 PowerShell, like most command-line interfaces, will let you see a list of all the available cmdlets for your system.

  • To get a list of all available cmdlets for MSOnline, run this command:
Get-Command -module MSOnline
  • You can also run the same command to see the list of all available cmdlets for Azure Active Directory, just by replacing the -module variable:
Get-Command -module AzureAD

4. Get a list of all Office 365 users with PowerShell

One of the most common uses for Office 365 PowerShell is to get a list of all Office 365 users. In PowerShell, you can do that using just one cmdlet: Get-msoluser.

This cmdlet will return all Office 365 users with a valid license, and automatically retrieve some basic information on each: the DisplayName, City, Department and ObjectID parameters.

  • To do this, run:
Get-MsolUser | Select DisplayName, City, Department, ObjectID
  • You can then see the number of accounts by running a similar command:
Get-MsolAccountSku
  • And to list the services you have available, run this command:
Get-MsolAccountSku | select -ExpandProperty ServiceStatus

These commands can then be expanded to filter the results returned, using standard command-line logic. For instance, you can group all of the users in a particular location by running:

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

This will display a list of all users, as before, but now sorted by location.

5. Creating a New User in Office 365 with PowerShell

Just as PowerShell allows you to quickly get a list of users, it can also be used to automate the process of creating new users for your system. To create a new user, you can make use of the New-MsolUser cmdlet:

  • To automate the process of user creation, use this cmdlet with the relevant variables:
New-MsolUser -UserPrincipalName JSmith@enterprise.onmicrosoft.com -DisplayName "John Smith" -FirstName “John” -LastName “Smith”
  • PowerShell will then output information on the user you have created, including their temporary password and their license status.

6. Removing a User From All Sites Using PowerShell

In order to remove a user from all sites and services, you will need to collect their login name, and a list of all the systems they have access to. This may sound like a complicated process, but thanks to sharing file links with passwords and other collaborative cloud-based storage solutions, it really isn’t anymore.

Then, you can use PowerShell to automate the process of removing them from each site:

  • Run the following command, replacing the variables with those relevant to your system and the target user:
Get-SPOSite | ForEach {Remove-SPOUser -Site $_.Url -LoginName " JSmith@enterprise.onmicrosoft.com"}

This cmdlet will then return the new status of the user.

7. Changing a password in Office 365 with PowerShell

One of the most common, and the most irritating, tasks for system administrators is to change a user’s password. Ideally, a shared program’s customers should be using a password manager, but PowerShell gives you the capability to automatically update the password for individual users:

  • To do that, run the following command:
Set-MsolUserPassword -UserPrincipalName JSmith@netwrixqcspa.onmicrosoft.com -NewPassword P@SSw0rd!
  • You can also omit the -NewPassword parameter, in which case the system will automatically generate a random password:
Set-MsolUserPassword -UserPrincipalName JSmith@netwrixqcspa.onmicrosoft.com

Windows PowerShell Commands for Reporting

PowerShell Command tip for reporting

Office 365 PowerShell is a great tool for making reports from Office 365. Using PowerShell cmdlets allows you to quickly and easily access, sort, and collate information on the users of your Office 365 environment, as well as information on the way that they are using the system.

You should note, however, that most of the reporting cmdlets were deprecated in January 2018. Microsoft replaced these cmdlets with the new MS Graph Reporting API. This reduced the capabilities of Office 365 PowerShell when it comes to making reports, but all of the old functionality is still available through the Office 365 Security & Compliance Center.

One area in which PowerShell for Office 365 is still a key tool, though, is when it comes to reporting on users, usage, and groups. These are among the most useful reports that PowerShell can be used for:

8. Licensing Plans

PowerShell comes with an extremely useful cmdlet that lets you see a summary of your current licensing plans and the available licenses for each plan. To do that:

  • Run the following code:
Get-MsolAccountSku

This will give you a report that has several key pieces of information:

  • AccountSkuld, which shows the available licensing plans for your organization,
  • ActiveUnits, which is the number of licenses that you’ve purchased for a specific licensing plan.
  • WarningUnits, which is the number of licenses in a licensing plan that you haven’t renewed, and that will expire after the 30-day grace period.
  • ConsumedUnits, the number of licenses that you’ve assigned to users from a specific licensing plan.

You can also use extra syntax with this same command to pull further information on your licenses or to filter and sort your results. For more information on how to do that, visit the Microsoft documentation on using PowerShell for reporting.

9. User Accounts

Another useful reporting cmdlet is Get-MsolUser, which will return a list of all the user accounts for your Office 365 setup. Here is how to use that command:

  • Run the command on its own:
Get-MsolUser
  • And you will see a full list of user accounts with their display names. You can also add a number of parameters, however, to filter the accounts that are displayed. For instance, to return a 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
  • To further investigate specific accounts, you can use the where cmdlet. To combine the two cmdlets, we use the “pipe” character “|”. This means that Office 365 PowerShell will take results of the first command and send it to the next command. For instance, if you want to display only those user accounts that have an unspecified usage location, you can use this command:
Get-MsolUser | Where {$_.UsageLocation -eq $Null}

By adding extra syntax after the pipe, you can make your reports more specific, and return users with any combination of attributes.

10. Email Reports

PowerShell can also be used as a powerful way of checking email usage and users, and in fact this is one of the major applications of the system when it comes to reporting. Here are some useful email reports:

  • You can get PowerShell to return details on every mailbox on your system using the following command:
Get-mailbox | get-MailboxStatistics
  • You can also use it to return a list of all the mailboxes that haven’t been logged into within 30 days (or any other period), which indicates that you need to close these boxes. To do that, run:
Get-Mailbox –RecipientType 'UserMailbox' | Get-MailboxStatistics | Sort-Object LastLogonTime | Where {$_.LastLogonTime –lt ([DateTime]::Now).AddDays(-30) } | Format-Table DisplayName, LastLogonTime
  • Another useful tool for cybersecurity is to check the activity of your mailboxes in order to check the boxes that are sending and receiving the most mail. There is a specific cmdlet for this task. Just run:
Get-MailTrafficTopReport
  • Finally, you can write a script to return a detailed report on all email groups and their members:
function Get-AllO365Members

{

Try

{

$O365Groups=Get-UnifiedGroup

foreach ($O365Group in $O365Groups)

{

Write-Host "Group Membership: " $O365Group.DisplayName -ForegroundColor Green

Get-UnifiedGroupLinks –Identity $O365Group.Identity –LinkType Members

Write-Host

}

}

catch [System.Exception]

{

Write-Host -ForegroundColor Red $_.Exception.ToString()

}

}

Get-AllO365Members

Office 365 PowerShell Cmdlets for Configuration

PowerShell Command tip for configuration

Office 365 PowerShell is also extremely useful when it comes to configuring your Office 365 environment. As we point out in our free video course on hidden Office 365 settings you can unlock with PowerShell, there are certain configuration settings that are only available through the PowerShell interface.

The most useful, and most commonly used, PowerShell commands for configuration are those that relate to managing user groups, and creating new SharePoint sites. These are both tasks that frequently complicate the workflow of system administrators, and automating them can save you a lot of time.

11. Configure “Hidden” Settings Using PowerShell for Office 365

As we’ve mentioned, there are some configuration settings for Office 365 that can only be accessed using PowerShell.

The clearest example of this are the configuration options for Skype for Business. The online admin center for this service contains a few options to allow you to customize the way it runs for your organization. However, there are more options if you are using PowerShell. For instance, as standard Skype meetings are set up so that:

  • Anonymous users can gain automatic entrance to each meeting.
  • Attendees can record the meeting.
  • All users from your organization can be designated as presenters.

To change these default settings, you can use Powershell. Here is a command that disables all three:

Set-CsMeetingConfiguration -AdmitAnonymousUsersByDefault $False -AllowConferenceRecording $False -DesignateAsPresenter "None"

If you want to reset the settings to default, use this command:

Set-CsMeetingConfiguration -AdmitAnonymousUsersByDefault $True -AllowConferenceRecording $True -DesignateAsPresenter "Company"

This is just one example of the hidden configuration settings you can access through PowerShell. To learn more, check out our free online course.

12. Managing Group Membership in Office 365 With PowerShell

PowerShell comes with several cmdlets specifically for working with Office 365 groups. For example:

  • Run the command:
Get-MsolGroup

To see a list of all the active groups in Office 365. This command will also give a hexadecimal ID for each group, which you will need to manage membership.

  • To add and remove group members, you will also need the hexadecimal ID of their user account, which you can get by running:
Get-MsolUser | Select ObjectID.
  • You can then run a related cmdlet to add or remove users from particular groups. To add users, for example, run the following command, replacing the hexadecimal IDs with those relevant to your group and the desired user:
Add-MsolGroupMember -GroupObjectId 5b61d9e1-a13f-4a2d-b5ba-773cebc08eec -GroupMemberObjectId a56cae92-a8b9-4fd0-acfc-6773a5c1c767 -GroupMembertype user
  • To remove users from groups, you can run the same command, but with:
Remove-MsolGroupMember

13. Creating a SharePoint site collection with PowerShell

The final useful command for Office 365 PowerShell is to use the command line to create new SharePoint site collections:

  • To do that, run the following command:
New-SPOSite -Url "https://enterprise.sharepoint.com/sites/NewSite" -Owner "JSmith@enterprise.onmicrosoft.com" -StorageQuota "100" -Title "New Site"

A Note on Internal Audits

While using Office 365 PowerShell is a powerful way to automate, manage, and report on your Office 365 system, you should take care when using it.

A critical part of keeping your active directory secure is to ensure that you carefully audit all the changes you make to Office 365 using PowerShell. Because of the power of the command-line interface, it is easy to apply changes to hundreds of user accounts at once, and this can cause operational issues and security vulnerabilities.

Having a reference of all the changes you have made will help you to troubleshoot issues, and to spot potential security flaws in your system.

How Varonis and Powershell Work Together

Varonis complements your PowerShell use in a few different ways.

Monitoring

Varonis monitors and audits Office 365 activity (including configuration changes) PowerShell commands so you can track any changes that admins or bad actors make with PowerShell.

Admins should only make changes to Office 365 configurations or permissions with a valid change request. This extra layer of validation keeps processes and procedures running smoothly.

Bad actors try to use PowerShell to disable security measures or escalate privileges of an account. Varonis catches those changes and tracks any other actions bad actors make in Office 365.

Take Action on Alerts

Varonis allows users to execute PowerShell scripts on alerts. Any response you can program is available from any custom or pre-built alert.

The most common situation we see in the field is an automated response to ransomware attacks. The ransomware threat model calls a script to disable the user account and power off any machines they are logged into, which stops the attack from progressing.

A Final Word

Office 365 PowerShell is a powerful way to work with Office 365. It allows you to quickly access information from the system, compile detailed reports, and perform bulk actions. It also gives you access to certain Office 365 features that are not available in any other way.

Connecting Powershell to Office 365 is relatively easy, and will give you access to all of the advanced features above. It will also allow you to more easily integrate your Office 365 environment with Varonis’ Data Security Platform, and thereby keep all of your sensitive data secure.

Jeff Petters

Jeff Petters

Jeff has been working on computers since his Dad brought home an IBM PC 8086 with dual disk drives. Researching and writing about data security is his dream job.

 

Does your cybersecurity start at the heart?

Get a highly customized data risk assessment run by engineers who are obsessed with data security.