#Install-Module -Name AzureADPreview
#Install-Module -Name ActiveDirectory
Import-Module ActiveDirectory
Import-Module AzureADPreview

$cred = Get-Credential

Connect-AzureAD -Credential $cred

$users = Get-ADUser -SearchBase ‘OU=Test Users, OU=CO Users, DC=CO ,DC=domain, DC=org’ -filter *

foreach ($user in $users)
{
    $email = $user.samaccountname + '@co.domain.org'
    $UserPrincipalName = $email

    $newemail = "SMTP:"+$email
    $mailattribute = $email
    #$DisplayName = $user.displayName
    #$sam = $_SamAccountName

    $account = Get-AzureADUser | Where-Object {$_.UserPrincipalName -eq $UserPrincipalName}
    Write-Host "UserPrincipalName: $UserPrincipalName"
    Get-AzureADUser -ObjectId $account.ObjectId | select Account }
Add-AzureADGroupMember -ObjectId (Get-AzureADGroup -SearchString "OfficeUsersTest").ObjectId -RefObjectId $account.ObjectId

This is going to be a script that runs nightly to double checkthat certain atributes have been created for new User accounts.

  • @ech0OP
    link
    English
    3
    edit-2
    1 year ago

    I fixed the code. No longer getting that error. Here is the fixed code for future reference

    Import-Module AzureADPreview
    
    #Get Credentials to connect
    $Credential = Get-Credential
    
    Connect-AzureAD -Credential $Credential
    
    #Connect to Exchange Online
    Connect-ExchangeOnline -Credential $Credential -ShowBanner:$False
    
    $users = Get-ADUser -SearchBase ‘OU=Test Users, OU=Users,DC=co,DC=net’ -filter *
    
    foreach ($user in $users)
    {
        $email = $user.samaccountname + '@co.net'
        $UserPrincipalName = $email
    
        $newemail = "SMTP:"+$email
        $mailattribute = $email
        #$DisplayName = $user.displayName
        #$sam = $_SamAccountName
    
        Write-Host "UserPrincipalName: $UserPrincipalName"
        $account = Get-AzureADUser | Where-Object {$_.UserPrincipalName -eq $UserPrincipalName}
        Write-Host "Account: $account"
        
        if ($account -ne $null) {
            Get-AzureADUser -ObjectId $account.ObjectId | select Account
        
            # Add the user to the Azure AD group
            Add-AzureADGroupMember -ObjectId (Get-AzureADGroup -SearchString "OfficeUsersTest").ObjectId -RefObjectId $account.ObjectId
    
            #PowerShell to add a user to office 365 group
            Add-UnifiedGroupLinks -Identity [email protected] -LinkType "Members" -Links $email
        }
    }
    
            #Disconnect Exchange Online
            Disconnect-ExchangeOnline -Confirm:$False```