Hi @Rory_Feng ,
Welcome to Microsoft Q&A! Thanks for posting the question.
Apologies for the delayed response as I had been trying a few things locally. While I am not sure of the exact cause of the issue, here are 3 suggestions that should help resolve it or at least get more details on the error.
1. Wrap your 'Connect-AzAccount` in a retry logic for transient network failures, something like below. (Since you do not see the failure consistently, it seems to be a transient issue which resolves on its own after a few seconds. Adding retry logic would help overcome such condition):
# Wrap authentication in retry logic for transient network failures
[System.Int32]$LogonAttempt = 0
[System.Int32]$LogonAttemptMax = 3
[System.Boolean]$Connected = $false
while (($false -eq $Connected) -or ($LogonAttemptMax -le $LogonAttempt))
{
# Logging in to Azure...
$ConnectionResult = Connect-AzAccount `
-ServicePrincipal `
-Tenant $Connection.TenantID `
-ApplicationId $Connection.ApplicationID `
-CertificateThumbprint $Connection.CertificateThumbprint `
-ErrorAction "SilentlyContinue"
if ($ConnectionResult)
{
Write-Verbose -Message "Connected to Azure."
[System.Boolean]$Connected = $true
}
elseif ($LogonAttemptMax -le $LogonAttempt)
{
Write-Warning -Message "Not connected to Azure yet. Trying again in 10 seconds. Logon attempt: '$LogonAttempt' of: '$LogonAttemptMax'."
Start-Sleep -Seconds 10
$LogonAttempt++
}
else {
Write-Error -Message "An error ocurred while trying to connect to Azure after: '$LogonAttemptMax' attempts."
#exit runbook because we were not able to connect.
exit 1
}
}
2. To get the exact location where the error is happening, you can use the snippet below in catch{}
block:
catch
{
write-error $_.Exception.Message
#The scriptStackTrace would contains the line number for faulting code
write-error $_.ScriptStackTrace
throw ($_)
}
3. I see you are starting the runbook at 0:00. Can you please change it to something like 0:05 AM. This is to avoid ambiguous DateTime from schedule, just to be on the safer side.
Please let me know if you have any questions.
---
Please 'Accept as answer' and ‘Upvote’ if it helped so that it can help others in the community looking for help on similar topics.