Skip to content

Invoke-MgGraphRequest resets Environment #1312

Closed
@remyloy

Description

@remyloy

After a call to Invoke-MgGraphRequest the selected environment through Connect-MgGraph is not restored.
The following snippet shows this issue by adding a test environment, which is configured the same as the built-in Global environment.

Just for clarification, this is a simplification for demonstrating the issue. In my production code the environment uses a different graph endpoint.

#Requires -Modules @{ModuleName = "Microsoft.Graph.Authentication"; ModuleVersion = "1.9.6" }

# Connection parameters
$Params = @{
    ClientId              = ''
    TenantId              = ''
    CertificateThumbprint = ''
}
$TestEnv = Add-MgEnvironment -Name 'Test' -AzureADEndpoint 'https://login.microsoftonline.com' -GraphEndpoint 'https://graph.microsoft.com'
try
{
    Connect-MgGraph @Params -Environment $TestEnv.Name | Out-Null
    if ($null -eq [Microsoft.Graph.PowerShell.Authentication.GraphSession]::Instance.Environment)
    {
        Write-Error -Message 'Env not set (before Invoke-MgGraphRequest) '
    }

    Invoke-MgGraphRequest -Uri '/v1.0/users' | Out-Null

    if ($null -eq [Microsoft.Graph.PowerShell.Authentication.GraphSession]::Instance.Environment)
    {
        Write-Error -Message 'Env not set (after Invoke-MgGraphRequest)'
    }
}
finally
{
    Disconnect-MgGraph
    Remove-MgEnvironment -Name $TestEnv.Name | Out-Null
}

The error is written after Invoke-MgGraphRequest, as the environment is then null instead of being the Test environment.

My current workaround is to call Connect-MgGraph, before each call to Invoke-MgGraphRequest, to ensure the expected environment is actually used.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions