Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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
} 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

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
} 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...