In Powershell how can I remove the first x number of characters from Get-ADUser results?

  active-directory, powershell, windows

I have a list of results from Get-ADUser giving me all users in an OU. The format of the output username is ‘-prefix-username’. I need to remove the 7 character ‘-prefix-‘ and then conduct another Get-ADUser lookup against the remaining ‘username’ portions. The issue I’m finding is that if I run just the second Get-ADUser lookup where I set $User as just one specific ‘-prefix-username’ it works fine but when I try to process a list I either get an error where there seems to be space after the trimmed username (txt format list – Get-ADUser : Cannot find an object with identity: ‘user ‘ under:) or the username includes a " that I can’t remove from the end of the username (csv format list – Get-ADUser : Cannot find an object with identity: ‘user"’).

So far I have:

get-ADUser -Filter * -SearchBase 'OU=SomeOU' -SearchScope 2 | 
Select SAMAccountName | 
Out-File C:TempUserList.txt

$UserList = (Get-Content C:TempUserList.txt)

$StandardUsers = ForEach($User in $UserList) {
   
    Write-Host "Now checking $User"
    Get-ADUser $User.Substring(7) -Properties * | 
    Select-object DisplayName, UserPrincipalName, Mail, Manager,EmployeeID    
    }
    $StandardUsers | Out-File -FilePath C:TempStandardUserList.txt

Source: Windows Questions

LEAVE A COMMENT