Running the below code and trying to get value from Azure AD using Automation runbook account.Its giving permission denied error. I have Followed these steps, Still unable to get a result. please let me know if someone faces a similar issue or know how to solve it
Code:
$connectionName = "AzureRunAsConnection"
# Get the Service Principal connection details for the Connection name
$servicePrincipalConnection = Get-AutomationConnection -Name $connectionName
# Logging in to Azure AD with Service Principal
"Logging in to Azure AD..."
Connect-AzureAD -TenantId $servicePrincipalConnection.TenantId `
-ApplicationId $servicePrincipalConnection.ApplicationId `
-CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
"List Tenant Org Details:"
Get-AzureADTenantDetail | Select DisplayName, Street, PostalCode, City, CountryLetterCode
"Member Account Synced Count:"
(Get-AzureADUser -All $true -Filter "userType eq 'Member' and accountEnabled eq true" | Where-Object {$_.DirSyncEnabled -eq $true}).Count
"Disabled Users Count:"
(Get-AzureADUser -All $true -Filter 'accountEnabled eq false').Count
"Guest User Count:"
(Get-AzureADUser -All $true -Filter "userType eq 'Guest'").Count
"Cloud Only Account Count:"
(Get-AzureADUser -All $true -Filter "userType eq 'Member'" | Where-Object {$_.userPrincipalName -like "*onmicrosoft.com"}).Count
Error:
Get-AzureADUser : Error occurred while executing GetUsers Code: Authorization_RequestDenied Message: Insufficient privileges to complete the operation. RequestId: "" DateTimeStamp: Fri, 26 Jun 2020 04:07:45 GMT HttpStatusCode: Forbidden HttpStatusDescription: Forbidden HttpResponseStatus: Completed
At line:21 char:2
- (Get-AzureADUser -All $true -Filter "userType eq 'Guest'").Count
-
+ CategoryInfo : NotSpecified: (:) [Get-AzureADUser], ApiException + FullyQualifiedErrorId : Microsoft.Open.AzureAD16.Client.ApiException,Microsoft.Open.AzureAD16.PowerShell.GetUser
Directory.Read.All
). If you already added the perminssion, please don't forget grant admin consent for it. And please open another powershell window to re-connect with service principal and then try to doGet-AzureADUser
command because maybe there's a caching problem in powershell window. – Hury Shen