Smooth Google migration

Migrate from Google Drive to M365 the right way

Learn more
Take this quiz to discover your Copilot risk detection score
Is your Copilot deployment helping your users or exposing your data?

Microsoft 365 governance made simple

Fix what matters, faster, without complex rules or tool switching!

Free trial

Master Hacks: Migrate like a pro

Check out our video series to help you turn migration projects into masterpieces!

Watch now

Table of contents

While the Microsoft 365 admin center supports many bulk and administrative tasks, some advanced or highly repetitive operations can be more efficient when automated with PowerShell.

With the right scripts, you can automate common admin tasks, speed up routine processes, and gain more control over your environment

But while PowerShell is a powerful tool, not everyone wants to live in scripts all day—especially since they can be difficult to maintain, secure, and govern as environments grow. That’s why many IT teams pair scripting with purpose-built tools like ShareGate to simplify complex tasks and cover more ground. 

In fact, ShareGate Migrate handles large-scale migrations without the need for scripting, while our PowerShell module offers powerful cmdlets for those who prefer a more hands-on approach. 

In this guide, we’ll cover four PowerShell automation script examples you can start using today to get more done with less manual effort. 

Why use PowerShell automation for Microsoft 365?

PowerShell gives IT admins a way to automate routine work, apply changes at scale, and streamline day-to-day operations. Here’s why many turn to PowerShell as part of their toolkit:

  • Speed: Run a single script to update thousands of users, review permissions, or adjust configurations. Even basic scripts can dramatically cut down on manual work.
  • Repeatability: Once you’ve written a script, you can reuse it any time. The extra upfront effort lets you automate workflows, offering long-term savings and consistency.
  • Bulk changes: PowerShell integrates with key Microsoft 365 services, making it easier to automate administrative tasks and make bulk changes, like policy configurations or permissions shifts, with one command.

PowerShell is especially useful for repetitive or large-scale admin projects that the admin center just isn’t built to handle efficiently. That said, it’s not a complete solution on its own. For more complex scenarios—like managing migrations or applying governance at scale—pairing PowerShell with solutions like ShareGate can give you the best of both worlds: automation where it helps, and simplicity where it counts.

Getting started with PowerShell scripting

PowerShell uses cmdlets that can be combined with functions, pipelines, and modules to perform administrative tasks. When you group these commands into scripts, you’ve got a flexible automation tool that can save time and reduce manual effort.

New to scripting? PowerShell has a learning curve, but admins can start with simple scripts before gradually building more advanced automation. Here are the basics to get up and running:

  1. Install required modules: PowerShell needs modules to communicate with your M365 environment. Common modules include Microsoft.Graph or ExchangeOnlineManagement.
  2. Connect to Microsoft 365 services: Use Connect-MgGraph for Microsoft Graph or Connect-ExchangeOnline for Exchange Online, depending on which services you’re working with.
  3. Write a basic script: Once connected, you can create .ps1 scripts to list users, review permissions, or check mailbox sizes. Start with simple tasks and expand as you go—PowerShell rewards iteration.

Before rolling out any script, always test it in a safe environment. You’ll want to see how it behaves and catch any issues before applying changes to your production setup.

And one last tip: Use comments generously. Even if the script makes perfect sense now, you may find that it doesn’t a few months down the line. Clear comments help your future self—and anyone else reading your code—understand what’s happening and why.

PowerShell is a great way to build automation into your admin workflows. And when combined with tools like ShareGate, you can extend that efficiency to areas like migration planning, reporting, and governance—without writing every script from scratch.

4 practical PowerShell scripting examples

Here’s a few real-world examples of what you can automate with PowerShell.

1. Assign site collection administration in SharePoint using PowerShell

You can manually add site collection admins through the SharePoint admin center. But who wants to do things manually? PowerShell scripting allows you to perform this task programmatically instead of manually through the admin center:

## Start by assigning variables in SharePoint as follows:

$AdminURL = "https://contoso-admin.sharepoint.com"

$AdminName = "admin@contoso.onmicrosoft.com"

$SiteCollectionURL = "https://contoso.sharepoint.com/sites/marketing"

$SiteCollectionAdmin = "Mark@sharegate.onmicrosoft.com"

## Connect to SharePoint Online using modern authentication (MFA supported)

Connect-SPOService -Url $AdminURL

## Finally, add the site collection admin, and you're done!

Set-SPOUser -site $SiteCollectionURL -LoginName $SiteCollectionAdmin -IsSiteCollectionAdmin $True

2. Export a list of all SharePoint site collections

PowerShell lets you export a list of SharePoint site collections and their properties:

# 1. Import the SharePoint Online Management Shell module

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

# 2. Set your SharePoint admin center URL

$AdminCenterUrl = "https://<yourtenant>-admin.sharepoint.com"

# 3. Connect to SharePoint Online

Connect-SPOService -Url $AdminCenterUrl

# 4. Retrieve all site collections in the tenant

$AllSites = Get-SPOSite -Limit All -IncludePersonalSite $true

# 5. Select the properties you want to export

#    Adjust or add additional properties as needed

$SiteReport = $AllSites | Select-Object `

    Title, `

    Url, `

    Owner, `

    Template, `

    StorageQuota, `

    StorageUsageCurrent, `

    LastContentModifiedDate, `

    SharingCapability

# 6. Export the report to CSV

$CsvPath = "C:\Temp\SharePointSiteCollections.csv"

$SiteReport | Export-Csv -Path $CsvPath -NoTypeInformation -Encoding UTF8

Write-Host "Export complete. File saved to $CsvPath"

3. Use PowerShell to copy a team

Need to duplicate an M365 team? PowerShell can help recreate parts of a Team (such as members and channels), but it won’t clone underlying content (like channel messages/files), and tabs may require reconfiguration after cloning:

# Connect to Microsoft Graph with necessary permissions

Connect-MgGraph -Scopes "Team.Create","Group.ReadWrite.All","Directory.ReadWrite.All"

# Define source team ID and new team properties

$sourceTeamId = "<SOURCE_TEAM_ID>"

$body = @{

    displayName    = "New Team Copy"

    description    = "Cloned team from existing team"

    mailNickname   = "newteamcopy$(Get-Random)"

    visibility     = "Private"  # or "Public"

    partsToClone   = "apps,tabs,settings,channels,members"

}

# Clone the team (structure, channels, members, apps, settings)

Copy-MgTeam -TeamId $sourceTeamId -BodyParameter $body

Write-Host "Clone initiated for team ID $sourceTeamId"

4. Copy user permissions in SharePoint using PowerShell

There’s no single PowerShell cmdlet that copies SharePoint permissions. Instead, permissions are read from one location and reapplied to another, which means you need to account for inheritance, group membership, and role assignments.

PowerShell can help replicate permissions at scale by reconstructing them rather than performing a true copy.

Example: Replicate site permissions using PowerShell

This example shows how to copy SharePoint group permissions from one site to another:

# Connect to the source site

Connect-PnPOnline -Url "https://contoso.sharepoint.com/sites/source" -Interactive

# Capture group permissions

$Groups = Get-PnPGroup | ForEach-Object {

    [PSCustomObject]@{

        Name  = $_.Title

        Roles = (Get-PnPGroupPermissions -Identity $_.Title).RoleDefinitionBindings.Name

    }

}

# Connect to the target site

Connect-PnPOnline -Url "https://contoso.sharepoint.com/sites/target" -Interactive

# Break inheritance on the target site

$web = Get-PnPWeb

$web.BreakRoleInheritance($false, $true)

$web.Update()

Invoke-PnPQuery

# Reapply permissions

foreach ($Group in $Groups) {

    if (-not (Get-PnPGroup -Identity $Group.Name -ErrorAction SilentlyContinue)) {

        New-PnPGroup -Title $Group.Name

    }

    Set-PnPGroupPermissions -Identity $Group.Name -AddRole $Group.Roles

}

Keep in mind that SharePoint permissions are highly contextual. Inherited permissions, missing users, or different site structures can all affect the outcome. For large environments or ongoing governance, managing permissions exclusively through scripts can quickly become difficult to maintain. Tools like ShareGate help simplify permissions management without rebuilding everything manually.

Best practices for building reliable PowerShell scripts

PowerShell can make a world of difference when it comes to automation. But that’s only the case if your scripts are reliable and secure. 

Here are a few best practices to keep you on the right track.

Use parameterization for flexibility

Parameterization—instead of hard-coding values—gives your scripts more flexibility. You can reuse a script with parameterized inputs across different environments and in distinct use cases. All you need to do is adjust the input values and your script will adapt. Easy, quick, and endlessly reusable.

Avoid hard-coding values wherever possible as it instantly limits the flexibility of your scripts.

Log script outputs for easier troubleshooting

The more information you have on a script during execution, the easier it becomes to troubleshoot. Log everything your script does and track errors and actions over time.

You can use logging mechanisms such as Start-Transcript or writing to a log file using Out-File or Add-Content. This is a win-win: You’re enhancing visibility into your scripts and also making them easier to debug. It’s worth taking a little extra time while scripting to ensure they remain usable and flexible. 

Handle errors with try/catch

Think of try/catch blocks as safety nets in your code. Whenever your scripts try something and it fails, your catch section will execute a specific action. Instead of just breaking when your code fails, this means you can try to catch and cover the issue more effectively.

Wrap any sections of code with the try action if you worry they might fail. Then, specify the catch action it creates, like sending an alert to you. You can also build logging into the process, which will help detect why a try block might be failing in the first place.

Keep scripts version controlled

A great PowerShell script is a tool that you and developers in your company will use for years. With that in mind, you may not be the only one that interacts with a script. Script version history works to keep your team on the same page so everyone is receiving the same reliable information. Your version control hub will include your most recent version for people to work from. 

Over time, versioning creates a lineage of who changed what about a script, what’s evolved, and what improvements happened along the way. And if something does go wrong, you’re covered—just roll it back when you’re in doubt. 

Take M365 automation to the next level with ShareGate

PowerShell is a powerful way to automate Microsoft 365 admin tasks, from managing permissions to running reports. But scripting isn’t always quick or intuitive, especially when you’re short on time or need broader visibility across your environment.

ShareGate brings the power of automation to your everyday M365 tasks. ShareGate’s UI provides many no-code automation capabilities, and for scenarios where you do want scripting, ShareGate’s PowerShell module gives you cmdlets tailored to ShareGate workflows. From bulk edits to permissions reviews and content moves, ShareGate helps you get more done, faster, with tools that are easy to use and ready to go out of the box.

Ready to simplify your Microsoft 365 management with ShareGate’s intuitive automation tools? Request a demo today.