Learning and Sharing
  • Home
  • Blog
  • Linux
  • macOS
  • VirtualBox
  • VMware
  • Windows
  • 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
  • VirtualBox
  • VMware
  • Windows
  • 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 Reinstall Microsoft Store in Windows after Uninstalling it with PowerShell

Next Post

How to Remove NuGet Package Provider Using PowerShell

Related Posts

Ftr21

Export Microsoft 365 Disabled Users Report Using Microsoft Graph

December 7, 2023
Ftr22

Export List of Users with Managers Name and UPN in Microsoft 365

December 7, 2023
Ftr38

How to Split an Email Addresses From @ with PowerShell

December 5, 2023
Ftr38

[WinForms] Creating GUIs in Windows PowerShell with WinForms

November 15, 2023
Ftr21

Converting DateTime Obtained from Microsoft Graph Call to PowerShell Date and Time Format

October 21, 2023
Ftr21

How to Get Microsoft 365 License Expiration Dates using Graph Api

December 7, 2023

Leave a Reply Cancel reply

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

Recent Posts

  • How to Enable Outlook Modern Authentication from Registry Setting
  • Export Microsoft 365 Disabled Users Report Using Microsoft Graph
  • Export List of Users with Managers Name and UPN in Microsoft 365

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 2023 © 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