Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

active directory - Add Azure group member from on perm AD powershell script

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
} 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
} 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...