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.
Locked
User avatar
ITEngineer
Posts: 210
Joined: Wed Oct 12, 2011 10:52 am

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: 14546
Joined: Tue May 22, 2007 9:57 am
Contact:

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: 210
Joined: Wed Oct 12, 2011 10:52 am

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 */

Locked