Forum Discussion
Unattended scripts do not connect to Azure AD
Hi,
I have a couple of scripts which should connect to Azure AD, to do whatever tasks and return some alarmistic over email.
I'm using this type of connection:
Connect-AzureAD -CertificateThumbprint "xxx" -ApplicationId "xxx" -TenantId "xxx"
If I run the scripts myself, everything runs well and I've got the expected output.
But when the scripts are run from a scheduled task, the connection to Azure AD is not successful, as I don't get the expected results.
Does anyone has had this issue before?
How can I troubleshoot this issue?
Thanks
Hi.
The first thing that comes to mind is: is the certification in your user store or the local machine store? If the scheduled task account can't see it and read the private key, that's one reason it could be failing.
You may want to log output from the Connect-AzureAD commandlet within the scheduled task out to a file to learn more:
$LogFile = "C:\Data\Temp\myScheduledTask.log"; Connect-AzureAD -CertificateThumbprint "xxx" -ApplicationId "xxx" -TenantId "xxx" *> $LogFile;
Cheers,
Lain
- LainRobertsonSilver Contributor
Hi.
The first thing that comes to mind is: is the certification in your user store or the local machine store? If the scheduled task account can't see it and read the private key, that's one reason it could be failing.
You may want to log output from the Connect-AzureAD commandlet within the scheduled task out to a file to learn more:
$LogFile = "C:\Data\Temp\myScheduledTask.log"; Connect-AzureAD -CertificateThumbprint "xxx" -ApplicationId "xxx" -TenantId "xxx" *> $LogFile;
Cheers,
Lain
- dmarquesgnIron Contributor
Hi,
Thanks. That was precisely the issue. It was a user based certificate and the script was running with a different user, so it didn't reach the other user certificate store.
Anyway, how can I add an extra step on the script to confirm if the Azure AD connection was successful, and if not, stop the script?
Thanks
- LainRobertsonSilver Contributor
You can use the -ErrorAction:Stop parameter, which I tend to use in a try...catch block.
For example:
$LogFile = "D:\Data\Temp\myScheduledTask.log"; Remove-Item -Path $LogFile -ErrorAction:SilentlyContinue; try { $null = Connect-AzureAD -CertificateThumbprint "xxx" -ApplicationId "xxx" -TenantId "xxx" -ErrorAction:Stop; "$([datetime]::Now.ToString("u"))`: Successfully connected to Azure AD ..." | Out-File -FilePath $LogFile -Append; } catch { # Let's log the error to file before re-throwing it to the calling process. "$([datetime]::Now.ToString("u"))`: $($_.ScriptStackTrace)`n$($_.Exception)" | Out-File -FilePath $LogFile -Append; throw; }
You don't have to go to this extra effort though. Just using the -ErrorAction:Stop on the Connect-AzureAD is enough to halt the script.
Cheers,
Lain