Search code examples
replacetrim

I FIXED MY OWN: How to replace part of lastname in Active Directory


So I am trying to determine why the end of a Surname isn't being trimmed or replaced. I've used trim() and replace ("-Disabled, " ") so that I can get only the last name but it seems to not work. I've looked at various examples yet none seem to be working.

I am using Powershell

$results = Get-ADUser -Filter * -Properties Enabled,DisplayName | 
Where-Object{$_.Name -match $regex} | 
Select Name,SurName,DisplayName,Enabled

foreach ($user in $results) {
if ($user.DisplayName -like "*-DISABLED"){
    $SurName = $user.SurName
    $lastName = $SurName.replace("-Disabled"," ")
    write-host $lastname}}
}

Prints:

 Martin-DISABLED
 Oconnell-DISABLED
 Rodgers-DISABLED
 Hughes-DISABLED
 Anderson-DISABLED

Solution

  • This line of code seem to have taken the last name. It split the **name "-" disabled ** and took back the last name due to using [0]. If I used [-1] then it would have taken Disabled instead.

    CODE:

    $lastName = $SurName.split("-")[0]