Forum Discussion
MGraph suddenly stops working
Hi Harm,
I had some automation scripts running (for longer periods) where i had the same issue.
The script starts, after a while i get an error (authentication failure)
It seems that in Graph there's an expiry on an connection.
So after some time it will disconnect and you have to reconnect again.
I made a module built in my automations (connect graph with an app registration)
Then it checks each minute if the expiry will take place, if it will then it automaticly reconnects:
On top of the script:
function ConnectGraph {
# Populate with the App Registration details and Tenant ID
$appid = 'Your App-ID'
$tenantid = 'Your-Tentant-ID'
$secret = 'Your-Created-Secret'
$body = @{
Grant_Type = "client_credentials"
Scope = "https://graph.microsoft.com/.default"
Client_Id = $appid
Client_Secret = $secret
}
$connection = Invoke-RestMethod `
-Uri https://login.microsoftonline.com/$tenantid/oauth2/v2.0/token `
-Method POST `
-Body $body
$global:token = $connection.access_token
$global:secureToken = ConvertTo-SecureString $global:token -AsPlainText -Force
$global:expiresIn = $connection.expires_in
$global:lastConnectTime = Get-Date
Connect-MgGraph -AccessToken $global:secureToken
}
function EnsureGraphConnection {
if ((Get-Date) -gt $global:lastConnectTime.AddSeconds($global:expiresIn - 60)) {
Write-Host "Refreshing MSGraph connection..." -ForegroundColor Yellow
connectgraph
}
}
Then before running your code, kick of the function connectgraph, and set variable of $lastconnectiontime
connectgraph
Now your connected to MSGraph.
Build a loop (while) and put this part on top of that foreach loop:
$success = $false
while (-not $success) {
try {
EnsureGraphConnection
###Your code here###
$success = $true
} catch {
if ($_.Exception.Message -match "token is expired") {
Write-Host "Token expired. Reconnecting to MSGraph..." -ForegroundColor Yellow
EnsureGraphConnection
} else {
Write-Host "Something went wrong, retrying in 5 seconds..." -ForegroundColor Red
Start-Sleep -Seconds 5
}
}
}
after the else block you can also put "continue" to skip the current item