Single PowerShell Script to Install Multiple M365 Modules

This PowerShell blog post will show you how to install multiple Microsoft 365 and Azure modules using a single PowerShell script.

By default, the script installs the following PowerShell module (on Windows, macOS and Linux):

  • ExchangeOnlineManagement
  • SharePointPnPPowerShellOnline
  • Azure
  • MicrosoftTeams
  • Microsoft.Graph

You can easily add more PowerShell modules to the list, add them to the list and run the script.

The script also includes exception handling in case there is an error.

PowerShell Script

The script does the following: uninstall, install, import and check if the module has been loaded to the PowerShell session. The script has been tested on macOS and Windows.

# Define the modules and add more modules
$modules = @( 
    "ExchangeOnlineManagement",
    "SharePointPnPPowerShellOnline",
    "Azure",
    "MicrosoftTeams",
    "Microsoft.Graph"
    
    )

# Uninstall the modules if they exist
foreach ($module in $modules) {
    try {
        if (Get-Module -ListAvailable -Name $module) {
            Uninstall-Module -Name $module -AllVersions -Force -ErrorAction Stop
        }
    } catch {
        Write-Error "Failed to uninstall module ${module}: $_"    }
}

# Install the latest versions of the modules
foreach ($module in $modules) {
    try {
        Install-Module -Name $module -Force -ErrorAction Stop
    } catch {
        Write-Error "Failed to install module ${module}: $_"    }
    }


# Import the installed modules
foreach ($module in $modules) {
    try {
        Import-Module $module -ErrorAction Stop
    } catch {
        Write-Error "Failed to import module ${module}: $_"  }
    }


# Check if the modules are installed
foreach ($module in $modules) {
    try {
        Get-Module -ListAvailable $module -ErrorAction Stop
    } catch {
        Write-Error "Failed to get module ${module}: $_"    }
    }

If you have recommendations to improve the code, add your comments to this post.


by

Comments

One response to “Single PowerShell Script to Install Multiple M365 Modules”

  1. RDP Avatar
    RDP

    Graph beta seems to come up.

Leave a Reply

Your email address will not be published. Required fields are marked *

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