Learning and Sharing
  • Home
  • Blog
  • Linux
  • macOS
  • Virtualization
    • VMware
    • VirtualBox
  • Windows
    • Windows 11
    • Windows 10
    • Windows Server
  • Series
    • Symantec
    • Intune
    • Microsoft Azure
    • Powershell
    • VirtualBox
    • VMware
    • PowerShell Learning
    • Microsoft Graph
  • More
    • Auto Installation
    • AEC Installation
  • Contact
No Result
View All Result
  • Home
  • Blog
  • Linux
  • macOS
  • Virtualization
    • VMware
    • VirtualBox
  • Windows
    • Windows 11
    • Windows 10
    • Windows Server
  • Series
    • Symantec
    • Intune
    • Microsoft Azure
    • Powershell
    • VirtualBox
    • VMware
    • PowerShell Learning
    • Microsoft Graph
  • More
    • Auto Installation
    • AEC Installation
  • Contact
No Result
View All Result
No Result
View All Result

Automatically Installs Microsoft Graph PowerShell Module if not Installed Already When Run a Script

September 21, 2023
in Blog, Powershell
0
ADVERTISEMENT

Table of Contents

Automatically Installs Microsoft Graph PowerShell Module

We’ve to work with Microsoft Graph PowerShell fairly often on new computers. So, when run a Graph PowerShell script, we must install the Microsoft PowerShell module manually on each system. It’s bored task and take time because we’ve done it manually.

So, we decided to include a function into our script to check the Microsoft Graph module. If it hasn’t been installed, the script will install it automatically.

Below is a simple code, we just need to add it into the beginning of our script. It will check then install Microsoft Graph module automatically before running the rest parts of the script.

$MsGraphModule =  Get-Module Microsoft.Graph -ListAvailable
$MsGraphBetaModule =  Get-Module Microsoft.Graph.Beta -ListAvailable

if($MsGraphModule -eq $null){
    Set-PSRepository -Name "PSGallery" -InstallationPolicy Trusted
    Install-Module Microsoft.Graph -Scope CurrentUser -AllowClobber -Force
}elseif ($MsGraphBetaModule -eq $null) {
    Set-PSRepository -Name "PSGallery" -InstallationPolicy Trusted
    Install-Module Microsoft.Graph.Beta -Scope CurrentUser -AllowClobber -Force
}

Connect-MgGraph -Scopes "User.Read.All"

Custom the checking code

Additionally, you can modify the code as you need to meet your requirements. For example, we print the messages in the console when checking the module and more.

$MsGraphModule =  Get-Module Microsoft.Graph -ListAvailable

if($MsGraphModule -eq $null){
    Write-host "`nInstalling Microsoft Graph module..."
    Set-PSRepository -Name "PSGallery" -InstallationPolicy Trusted
    Install-Module Microsoft.Graph -Scope CurrentUser -AllowClobber -Force
    Write-host "Microsoft Graph module is installed in the machine successfully" -ForegroundColor Green
}else {
    Write-Host "`nThe Microsoft Graph module has been installed on this computer." -ForegroundColor Green
}

$MsGraphBetaModule =  Get-Module Microsoft.Graph.Beta -ListAvailable

if($MsGraphBetaModule -eq $null){ 
    Write-host "`nInstalling Microsoft Graph Beta module..."
    Set-PSRepository -Name "PSGallery" -InstallationPolicy Trusted
    Install-Module Microsoft.Graph.Beta -Scope CurrentUser -AllowClobber -Force
    Write-host "Microsoft Graph Beta module is installed in the machine successfully" -ForegroundColor Green
}else {
    Write-Host "The Microsoft Graph Beta module has been installed on this computer." -ForegroundColor Green
}

Connect-MgGraph -Scopes "User.Read.All"

The output when we ran the script on a computer that hasn’t been the Microsoft Graph module installed.

PS C:\> .\connect.ps1

Installing Microsoft Graph module...
Microsoft Graph module is installed in the machine successfully

Installing Microsoft Graph Beta module...
Microsoft Graph Beta module is installed in the machine successfully

If the computer has the module already installed. The messages below would be displayed on the screen.

PS C:\> .\connect.ps1

The Microsoft Graph module has been installed on this computer.
The Microsoft Graph Beta module has been installed on this computer.

Alternatively, you can create a PowerShell function that requires user’s confirmation. Users can type Y/N (Yes/No). Then script will continue or exit depending on your decision.

Function Connect-MicrosoftGraph {

    $MsGraphModule =  Get-Module Microsoft.Graph -ListAvailable
    if($MsGraphModule -eq $null){
        Write-host "Important: Microsoft Graph module is unavailable. It is mandatory to have this module installed in the system to run the script successfully." 
        $confirm = Read-Host Are you sure you want to install Microsoft Graph module? [Y] Yes [N] No  
        if($confirm -match "[yY]")
            Write-host "Installing Microsoft Graph module..."
            Install-Module Microsoft.Graph.Beta -Scope CurrentUser -AllowClobber
            Write-host "Microsoft Graph module is installed in the machine successfully" -ForegroundColor Magenta 
    }else {
        Write-host "Exiting. `nNote: Microsoft Graph module must be available in your system to run the script" -ForegroundColor Red
        exit 
    }

    $MsGraphModuleBeta =  Get-Module Microsoft.Graph.Beta -ListAvailable
    if($MsGraphModuleBeta -eq $null){
        Write-host "Important: Microsoft Graph Beta module is unavailable. It is mandatory to have this module installed in the system to run the script successfully." 
        $confirm = Read-Host Are you sure you want to install Microsoft Graph Beta module? [Y] Yes [N] No  
        if($confirm -match "[yY]")
            Write-host "Installing Microsoft Graph Beta module..."
            Install-Module Microsoft.Graph.Beta -Scope CurrentUser -AllowClobber
            Write-host "Microsoft Graph Beta module is installed in the machine successfully" -ForegroundColor Magenta 
    }else {
        Write-host "Exiting. `nNote: Microsoft Graph Beta module must be available in your system to run the script" -ForegroundColor Red
        exit 
    }

    Connect-MgGraph -Scopes "User.Read.All"
}

Connect-MicrosoftGraph

Get-MgUser -Top 5

Complete the script

Note Note: We recommend you use the code from our GitHub to get the latest version of the script.

When installing Microsoft PowerShell module, Windows requires you have to:

  • Update the NuGet package provider.
  • Update the PowerShellGet module.
  • Add the PSGalery as a trusted repository.

The completly script below will do all above tasks automatically without prompts user to confirm the installation.

#Required running with elevated right.
if (-not([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
   Write-Warning "You need to have Administrator rights to run this script!`nPlease re-run this script as an Administrator in an elevated powershell prompt!"
   break
}

#Configure Execution Policy
if ((Get-ExecutionPolicy) -notmatch "RemoteSigned") {
     Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope LocalMachine -Force
}

#Update the NuGet Provider if needed.
$nuGetPath = "C:\Program Files\PackageManagement\ProviderAssemblies\nuget\*\Microsoft.PackageManagement.NuGetProvider.dll"
$testPath = Test-Path -Path $nuGetPath
if ($testPath -match 'false') {
    Write-Host "`nInstalling NuGet Provider..."
    Install-PackageProvider -Name NuGet -Force | Out-Null
}

#Update the PowerShellGet if needed.
$PSGetCurrentVersion = (Get-PackageProvider -Name 'PowerShellGet').Version
$PSGetLatestVersion = (Find-Module PowerShellGet).Version
if ($PSGetCurrentVersion -lt $PSGetLatestVersion) {
    Write-Host "`nUpdating PowerShellGet Module from $PSGetCurrentVersion to $PSGetLatestVersion..."
    Install-Module -Name 'PowerShellGet' -Force
}


#We're installing from the PowerShell Gallery so make sure that it's trusted.
$InstallationPolicy = (Get-PSRepository -Name PSGallery).InstallationPolicy
if ($InstallationPolicy -match "Untrusted") {
   Write-host "`nConfiguring the PowerShell Gallery Repository..."
   Set-PSRepository -Name "PSGallery" -InstallationPolicy Trusted
}

$graphCurrentVersion = (Get-InstalledModule Microsoft.Graph -ErrorAction SilentlyContinue).Version
$graphLatestVerison = (Find-Module Microsoft.Graph).Version

#Checking the Microsoft Graph module for installation
if($graphCurrentVersion -eq $null){
    Write-host "`nInstalling Microsoft Graph module version $graphLatestVerison..."
    Install-Module Microsoft.Graph.Authentication -Scope CurrentUser -AllowClobber -Force
    Write-host "Microsoft Graph module version $graphLatestVerison is installed in the machine successfully" -ForegroundColor Green
}else {
    Write-Host "`nThe Microsoft Graph module version $graphCurrentVersion has been installed on this computer." -ForegroundColor Green
}

#Update to Microsoft Graph PowerShell SDK v2
if (($currentVersion -ne $null) -and ($graphCurrentVersion -lt $graphLatestVerison)) {
    Write-host "`nUpdating Microsoft Graph module from $graphCurrentVersion to $graphLatestVerison..."
    Update-Module Microsoft.Graph -Force
}

#Checking the Microsoft Graph Beta module for installation
$MsGraphBetaModule =  Get-Module Microsoft.Graph.Beta -ListAvailable
if($MsGraphBetaModule -eq $null){ 
    Write-host "`nInstalling Microsoft Graph Beta module ..."
    Install-Module Microsoft.Graph.Beta -Scope CurrentUser -AllowClobber -Force
    Write-host "Microsoft Graph Beta module is installed in the machine successfully" -ForegroundColor Green
}else {
    Write-Host "The Microsoft Graph Beta module has been installed on this computer." -ForegroundColor Green
}

Online code to checking the installation

Lastly, to make our script look cleaning to focus on other important parts. We’ve put it on GitHub then call it in other scripts by a single command as below.

#Checking the Microsoft Graph module for installation
Invoke-RestMethod bonguides.com/graph/checkmodule | Invoke-Expression

#Connect to Graph API
Connect-MgGraph -Scopes "User.Read.All"
Get-MgUser -All

Not a reader? Watch this related video tutorial:

5/5 - (1 vote)
Previous Post

How to Find Expiring Client Secrets Using Graph API and PowerShell

Next Post

How to Remove NuGet Package Provider Using PowerShell

Related Posts

Running Hyper-V and VMware Workstation on The Same Machine

August 15, 2024

How to Uninstall All Autodesk Products At Once Silently

July 29, 2024
Ftr5

How to Uninstall the Autodesk Genuine Service on Windows

July 29, 2024
Ftr19

How to Fix Windows Cannot Read the ProductKey From the Unattend Answer File in VirtualBox

July 26, 2024
Ftr25

How to Update Windows Terminal in Windows 10/11

July 26, 2024

How to Disable The Beep Sound in WSL Terminal on Windows

July 26, 2024

Leave a Reply Cancel reply

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

Recent Posts

  • How To Turn On uBlock Origin Extension in Chrome (2025)
  • Images Hidden Due To Mature Content Settings In CivitAI
  • Azure OpenAI vs Azure AI Hub, How to Choose the Right One for Your Needs

Categories

Stay in Touch

Discord Server

Join the Discord server with the site members for all questions and discussions.

Telegram Community

Jump in Telegram server. Ask questions and discuss everything with the site members.

Youtube Channel

Watch more videos, learning and sharing with Leo ❤❤❤. Sharing to be better.

Newsletter

Join the movement and receive our weekly Tech related newsletter. It’s Free.

General

Microsoft Windows

Microsoft Office

VMware

VirtualBox

Technology

PowerShell

Microsoft 365

Microsoft Teams

Email Servers

Copyright 2025 © All rights Reserved. Design by Leo with ❤

No Result
View All Result
  • Home
  • Linux
  • Intune
  • macOS
  • VMware
  • VirtualBox
  • Powershell
  • Windows 10
  • Windows 11
  • Microsoft 365
  • Microsoft Azure
  • Microsoft Office
  • Active Directory

No Result
View All Result
  • Home
  • Linux
  • Intune
  • macOS
  • VMware
  • VirtualBox
  • Powershell
  • Windows 10
  • Windows 11
  • Microsoft 365
  • Microsoft Azure
  • Microsoft Office
  • Active Directory