Home > Software design >  PowerShell: Remove a portion of displayname
PowerShell: Remove a portion of displayname

Time:03-31

I need to remove a portion of the displayname of some guest users in Azure AD.

Displayname: Company - Firstname Lastname (Company - needs to be removed)

The guest accounts don't have 'Firstname' and 'Lastname' attribute filled in. I have a script running that can add something to a displayname:

#Guest CompanyNames
$Companies = @('Company1','Company2')

#Get guest users with UPN like: company.extension#EXT#@domain.onmicrosoft.com
Foreach ($Company in $Companies){
    $Users = Get-AzureADUser -All $true | Where-Object {($_.UserPrincipalName -like "*$Company.*") -and ($_.DisplayName -notlike "*($Company)")}

    foreach ($User in $Users){
        $DisplayName = $User.DisplayName   " "   "($Company)"
        Set-AzureADUser -ObjectId $User.ObjectId -Displayname $DisplayName
    }
    
}

I cannot find anything to tweak this kind of script to remove 'Company -' from a displayname. Hope someone can help me out, thanks!

CodePudding user response:

To do the opposite of your posted code, i.e. removing the company name that starts off the displayname, you might use this:

$Companies = 'Company1','Company2'
# join the company names with regex 'OR' ('|')
$regexCompanies = '^({0})\s*-\s*' -f (($Companies | ForEach-Object { [regex]::Escape($_) }) -join '|')

# find users that have a DisplayName starting with one of the company names
$Users = Get-AzureADUser -All $true | Where-Object {$_.DisplayName -match $regexCompanies}
foreach ($User in $Users) {
    # split the displayname in two parts, take the last part and trim it
    $DisplayName = ($User.DisplayName -split '\s*-\s*', 2)[-1].Trim()
    Set-AzureADUser -ObjectId $User.ObjectId -Displayname $DisplayName
}

BTW. Inside your foreach ($User in $Users) loop, you should be using $User, not $Users..

  • Related