this post was submitted on 09 Aug 2023
5 points (100.0% liked)

PowerShell

310 readers
1 users here now

A community dedicated to Microsoft PowerShell.

Rules

  1. Everyone is welcome.
  2. Treat others with respect at all time.
  3. When asking questions, please try to show what you have done, including code.

founded 2 years ago
MODERATORS
 
#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.

top 1 comments
sorted by: hot top controversial new old
[–] ech0 3 points 1 year ago* (last edited 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```