AskMe
AskMe

Reputation: 2571

Set-AzureADUser : Error occurred while executing SetUser Code: Authentication_Unauthorized

I'm new to PowerShell and getting below error: The users exists, How to fix this issue? Thanks.

PS C:\WINDOWS\system32> Set-AzureADUser -ObjectId [email protected] - AccountEnabled $false

Set-AzureADUser : Error occurred while executing SetUser
Code: Authentication_Unauthorized
Message: User was not found.
RequestId: b32c6fe2-d785-4d30-acc1-67ffba685269
DateTimeStamp: Sat, 20 Aug 2022 16:45:06 GMT
HttpStatusCode: Forbidden
HttpStatusDescription: Forbidden
HttpResponseStatus: Completed
At line:1 char:1
+ Set-AzureADUser  -ObjectId [email protected] -Account ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [Set-AzureADUser], ApiException
+ FullyQualifiedErrorId : 
Microsoft.Open.AzureAD16.Client.ApiException,Microsoft.Open.AzureAD16.PowerShell.SetUser

PS C:\WINDOWS\system32>

Upvotes: 0

Views: 2864

Answers (1)

Rukmini
Rukmini

Reputation: 15674

I tried to reproduce the same in my environment and got the same error when I tried to connect with wrong Tenant-ID:

 Set-AzureADUser -ObjectId UPN -AccountEnabled $false

enter image description here

The error usually occurs, if you are connecting Azure AD with Insufficient privileges (user has no admin privileges) or connecting with the wrong Tenant-ID .

To resolve the error, try connecting Azure AD by using below commands:

Connect-AzureAD -TenantId **** 
Get-AzureADDomain

enter image description here

Make sure the AuthenticationType is Managed while running Get-AzureADDomain command.

After connecting Azure AD with the required privileges and correct Tenant-ID , I am able to set the user successfully like below:

 Set-AzureADUser -ObjectId UPN -AccountEnabled $false

enter image description here

To confirm the above, you can also check in the Portal:

enter image description here

UPDATE:

To disable bulk Azure AD users, please try the below:

CSV file: enter image description here

$CSVrecords = Import-Csv "C:\Users\file.csv"
foreach ($CSVrecord in $CSVrecords) {
$ObjectID = $CSVrecord.ObjectID
$user = Get-AzureADUser -ObjectID "$ObjectID"
if ($user) {
try{
Set-AzureADUser -ObjectId $ObjectID -AccountEnabled $false
} catch {
$FailedUsers += $ObjectID
Write-Warning "$ObjectID user found, but FAILED to update."
}
}
else {
$SkippedUsers += $ObjectID
Write-Warning "$ObjectID not found, skipped"
}
}

I am able to disable the users successfully like below:

enter image description here

Upvotes: 1

Related Questions