Looking to run a Powershell update for Azure from a list.

Copper Contributor

 

c:\Temp\userlist.csv looks like

user@testdomain.com

user2@testdomain.com

 

 

# Assign the values to the variables
$username = get-content -path "c:\Temp\userlist.csv"
$app_name = "custom_app"
$app_role_name = "custom_role"

ForEach-Object{

# Get the user to assign, and the service principal for the app to assign to
$user = Get-AzureADUser -ObjectId "$username"
$sp = Get-AzureADServicePrincipal -Filter "displayName eq '$app_name'"
$appRole = $sp.AppRoles | Where-Object { $_.DisplayName -eq $app_role_name }

# Assign the user to the app role
New-AzureADUserAppRoleAssignment -ObjectId $user.ObjectId -PrincipalId $user.ObjectId -ResourceId $sp.ObjectId -Id $appRole.Id
}

 

I seem to be having a problem on the "$user" line

 

Get-AzureADUser : Error occurred while executing GetUser
Code: Request_ResourceNotFound
Message: Resource 'user@testdomain.com' does not exist or one of its queried reference-property objects are not present.
RequestId: 489b00fe-2e1c-4864-a859-8072555808b0
DateTimeStamp: Fri, 04 Jun 2021 20:54:09 GMT
HttpStatusCode: NotFound
HttpStatusDescription: Not Found
HttpResponseStatus: Completed
At line:8 char:9
+ $user = Get-AzureADUser -ObjectId "$username"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-AzureADUser], ApiException
+ FullyQualifiedErrorId : Microsoft.Open.AzureAD16.Client.ApiException,Microsoft.Open.AzureAD16.PowerShell.GetUser

1 Reply

Hello @Mike_F_MF,

I think you have a problem in your Foreach-Object statement.
If you want to use ForEach-Object you need to pipe (|) some collection to it.
In your case you can run something like this:

$username | ForEach-Object{

# Get the user to assign, and the service principal for the app to assign to
$user = Get-AzureADUser -ObjectId $_
$sp = Get-AzureADServicePrincipal -Filter "displayName eq '$app_name'"
$appRole = $sp.AppRoles | Where-Object { $_.DisplayName -eq $app_role_name }

# Assign the user to the app role
New-AzureADUserAppRoleAssignment -ObjectId $user.ObjectId -PrincipalId $user.ObjectId -ResourceId $sp.ObjectId -Id $appRole.Id
}

Another option would be to use foreach($item in $Collection){...} :

foreach($u in $username){
# Get the user to assign, and the service principal for the app to assign to
$user = Get-AzureADUser -ObjectId $u
$sp = Get-AzureADServicePrincipal -Filter "displayName eq '$app_name'"
$appRole = $sp.AppRoles | Where-Object { $_.DisplayName -eq $app_role_name }

# Assign the user to the app role
New-AzureADUserAppRoleAssignment -ObjectId $user.ObjectId -PrincipalId $user.ObjectId -ResourceId $sp.ObjectId -Id $appRole.Id
}

Hope that helps.