Connect-MgPermissions.psm1

function Connect-MgPermissions {
    <#
    .SYNOPSIS
    Connects to Microsoft Graph with the necessary permissions for specified cmdlets.
 
    .DESCRIPTION
    The Connect-MgPermissions function takes one or more Microsoft Graph cmdlets as input and determines the required
    permissions to run those cmdlets. It then attempts to connect to Microsoft Graph with those permissions.
 
    .PARAMETER Cmdlet
    One or more Microsoft Graph cmdlets for which to gather permissions.
 
    .EXAMPLE
    PS> Connect-MgPermissions -Cmdlet "Get-MgUser", "Get-MgGroup"
 
    This example gathers the permissions required for the Get-MgUser and Get-MgGroup cmdlets and connects to Microsoft Graph
    with those permissions.
 
    .NOTES
    The function requires the Microsoft.Graph module to be installed.
    #>

    
    [cmdletbinding()]
    param(
        [parameter(Mandatory, ValueFromPipeline = $false, HelpMessage = "Enter one or more Microsoft Graph cmdlets to gather permissions")]
        [string[]]$Cmdlet
    )

    BEGIN {
        # Check if the Microsoft.Graph module is installed
        try {
            Get-InstalledModule -Name microsoft.graph -ErrorAction Stop *> $null
        } 
        catch  { 
            # If not installed, prompt the user to install it
            Write-Host "Microsoft.Graph not installed, run: " -ForegroundColor Red -NoNewline
            Write-Host "Install-Module -Name Microsoft.Graph" -ForegroundColor Cyan
            return
        }
    }

    PROCESS {
        # Initialize a variable to store the required permissions
        $scope = foreach ($c in $Cmdlet) {
            try {
                # Find the permissions required for each cmdlet
                Find-MgGraphCommand $c -ErrorAction Stop | 
                    Select-Object -First 1 | 
                    Select-Object -ExpandProperty permissions | 
                    Where-Object isadmin -eq $true | 
                    Select-Object -ExpandProperty name
            } 
            catch { 
                # Handle any errors that occur during permission retrieval
                Write-Host "$($Error[0].Exception.Message)" -ForegroundColor Red
                return
            }    
        }

        # Remove duplicate permissions
        $scope = $scope | Select-Object -Unique

        # Display the permissions that will be used for the connection
        Write-Host "Connecting with permission(s): " -NoNewline
        Write-Host "$($scope -join ', ')" -ForegroundColor Cyan
        
        try {
            # Attempt to connect to Microsoft Graph with the required permissions
            Connect-MgGraph -Scopes $scope -ErrorAction Stop
        } 
        catch { 
            # Handle any errors that occur during the connection attempt
            Write-Host "$($Error[0].Exception.Message)" -ForegroundColor Red 
        }
    }
}