Hello @Sudhirkumar Karamchand !
Thank you for posting on Microsoft Learn.
I think you have an issue in the context or environment difference happening between manual and scheduled runs of your trigger function.
When you run it manually, your PowerShell function has access to your interactive identity/session (especially in development or testing via VS Code / Azure Portal). But during scheduled execution, it's fully reliant on non-interactive SPN auth (Service Principal with certificate thumbprint) which is where the problem typically lies.
You mentioned:
Connect-AzAccount -ServicePrincipal -Tenant $tenantId -CertificateThumbprint $thumb -ApplicationId $appId
However, later, when using:
Invoke-AzRestMethod -Method Get -Uri $uri
This may fail silently or return partial data when the token is missing scopes/permissions in the scheduled context.
When you use Connect-AzAccount with a certificate, the session token might not have access to Microsoft.Insights metrics APIs unless the SPN has monitoring reader or metrics reader roles.
If the schedule runs right on the hour, there may be a delay in the metrics being available (the API may return the metric, but the timeseries.data.average is missing because ingestion hasn’t completed).
The default Invoke-AzRestMethod request doesn't specify an explicit timespan, so it uses the default 1-hour window from current UTC time. During scheduled runs, that may yield no data, especially if metrics aren’t yet available for that window.
You may need to hardcode or dynamically generate a more stable window :
$endTime = (Get-Date).ToUniversalTime().AddMinutes(-5)
$startTime = $endTime.AddHours(-1)
$timespan = "$($startTime.ToString("s"))Z/$($endTime.ToString("s"))Z"
$uri = "https://management.azure.com$resourceId/providers/Microsoft.Insights/metrics?api-version=2023-10-01&metricnames=UsedCapacity&aggregation=Average×pan=$timespan"
The SPN (used in the certificate login) should have reader or monitoring reader role on the storage accounts or you can simply assign at subscription level if you're looping through many.
The REST call might succeed with a 200 but still contain no metrics, so try to add this inside the try block:
if (-not $metrics.value) {
Write-Warning "No metrics returned in scheduled run for $($storageAccount.StorageAccountName)"
}
Anothing thing that caught me, scheduled runs don't support interactive login so change this:
$ctx = New-AzStorageContext -StorageAccountName $storage_account -UseConnectedAccount
to:
$ctx = New-AzStorageContext -StorageAccountName $storage_account -UseManagedIdentity
Or reuse the existing SPN login (Connect-AzAccount), or use shared key if secure.