Reputation: 25
I have a Powershell script that runs every day on our on perm AD and making few actions for new employees. I'm trying also to add those users to one of our Azure AD groups (Add-AzureADGroupMember) but currently bo luck when trying to get the ObjectId.
Any idea what I'm doing wrong?
Import-Module ActiveDirectory
Import-module AzureAD
$tenantId = "1516515611561651651"
$azureUser = "[email protected]"
$AzureCredential = Get-Content "Encrypted.txt" | ConvertTo-SecureString -Key (1..16)
$AzureCred = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $AzureUser, $AzureCredential
$SearchBase = "OU=ou,DC=DC,DC=my"
Get-ADUser -SearchBase $SearchBase -Properties extensionAttribute1, mail, extensionAttribute12, userPrincipalName -Filter * | ForEach-Object {
# Connect to Azure AD
Connect-AzureAD -AccountId $azureUser -TenantId $TenantId -Credential $AzureCred
$objid= Get-AzureADUser -Filter "userPrincipalName eq '$_.userPrincipalName'" | select ObjectId
Add-AzureADGroupMember -ObjectId 6546fewf4s894f98sdfsd4f -RefObjectId $objid
}
Upvotes: 0
Views: 656
Reputation: 25001
Since Get-AzureADUser
parameter ObjectId
accepts a UPN value, you can simplify your syntax and remove the filtering. You also only need to connect to AzureAD once rather than for each user. Using -Expand
or -ExpandProperty
on Select-Object retrieves only the value of that property rather than an object that contains the property. Add-AzureAdGroupMember parameter -RefObjId
expects a string that contains only an objectID value.
Import-Module ActiveDirectory
Import-module AzureAD
$tenantId = "1516515611561651651"
$azureUser = "[email protected]"
$AzureCredential = Get-Content "Encrypted.txt" | ConvertTo-SecureString -Key (1..16)
$AzureCred = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $AzureUser, $AzureCredential
$SearchBase = "OU=ou,DC=DC,DC=my"
# Connect to Azure AD
Connect-AzureAD -AccountId $azureUser -TenantId $TenantId -Credential $AzureCred
Get-ADUser -SearchBase $SearchBase -Properties extensionAttribute1, mail, extensionAttribute12, userPrincipalName -Filter * | ForEach-Object {
$objid = Get-AzureADUser -ObjectId $_.userPrincipalName | Select -Expand ObjectId
Add-AzureADGroupMember -ObjectId 6546fewf4s894f98sdfsd4f -RefObjectId $objid
}
Upvotes: 1