Page 1 of 1

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

Posted: Thu Mar 14, 2019 5:19 am
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.

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

Posted: Thu Mar 14, 2019 5:38 am
by jvierra
Get-ADUser -Filter "Surname -eq '$lastName' -and GivenName -eq '$firstname'"

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

Posted: Thu Mar 14, 2019 9:42 pm
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.