Fixing PowerShell script to find AD user account based on Display Name or First.LastName?

Ask your PowerShell-related questions, including questions on cmdlet development!
Forum rules
Do not post any licensing information in this forum.

Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
This topic is 5 years and 1 week old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked
User avatar
ITEngineer
Posts: 216
Last visit: Thu Mar 23, 2023 5:45 pm
Has voted: 4 times

Fixing PowerShell script to find AD user account based on Display Name or First.LastName?

Post by ITEngineer »

Hello All,

I need some help in fixing the below PowerShell script to search for user samAccountName or Alias or Display Name like First Lastname in Active Directory from input typed by the user:

Code: Select all

Do {
    Write-Host -Object 'Enter a samaccountname / Alias or even "First Lastname", or nothing (Press Enter) to leave; wildcards and a space separated list are not supported.'
    $Input = Read-Host -Prompt 'User/List'
    If ($Input) {
        $(ForEach ($Username in $Input.Split(' ', [StringSplitOptions]::RemoveEmptyEntries)) {
                If ($ADUser = Get-ADUser -Filter {samAccountName -like $UserName} -Properties DisplayName) 
                {
                    Write-Verbose -Message "Processing $($ADUser.DisplayName)"
                    
                    "The samaccountname $($input) matching '$($UserName)'!"}
                    
                    Else {
                        "Could not find a user with a samaccountname matching '$($UserName)'!" | Write-Warning
                    }
                }
        
    )}
} Until (-not $Input)
The problem with the script is that I cannot find my username that I typed as First Lastname even if my AD account exists?

Thank you for the help so far.
/* IT Engineer */
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

Re: Fixing PowerShell script to find AD user account based on Display Name or First.LastName?

Post by jvierra »

Get-ADUser -Filter "Surname -eq '$lastName' -and GivenName -eq '$firstname'"
User avatar
ITEngineer
Posts: 216
Last visit: Thu Mar 23, 2023 5:45 pm
Has voted: 4 times

Re: Fixing PowerShell script to find AD user account based on Display Name or First.LastName?

Post by ITEngineer »

jvierra wrote: Thu Mar 14, 2019 5:38 am Get-ADUser -Filter "Surname -eq '$lastName' -and GivenName -eq '$firstname'"
Hm.. yes, that does make sense.
let me integrate to my script.
/* IT Engineer */
This topic is 5 years and 1 week old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked