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:
The problem with the script is as follows:
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)
When there is valid First.Lastname alias found the script is not showing any confirmation?
I cannot find my username that I typed as First Lastname even if my AD account is exist?
When there is a random string typed, it does not show about the error user cannot be found?
Don’t know how your AD attributes look like but the main problem as I see it is that you don’t consider what the user inputs.
You’re also only checking against the samAccountName attribute later on.
And with the split in the line before that you may end up with a firstname only which are then checked against the samAccountName.
My suggestion is that you first start with a single check for each scenario that you want to cover.
Like what Iain have given you a couple of examples of.
Once you got the Get-ADUser commands figured out then start building around that.
You will then also know what kind of input you need and check for.
What is the eventual goal here? The search is straight-forward, but what are you doing with the results? If you are doing and SET operations, this is a realllllllly bad idea. When you do any wildcard search and let users put what they want, it’s really dangerous, especially from a command line. Say you’re trying to create a process to reset a password. You type in Smith, find the smith and then the user needs to do a search for the full displayname again to return a single user to perform the SET operation. Even in the below example, without wrappers, you can just type nothing and it would return ALL users. Before you implement anything with this, you may want to ask the community how to solve the final solution you are working towards because wildcards are super dangerous.
With fair warning given, a basic example:
$usrinput = 'Simmers'
$search = "*$usrinput*"
$results = Get-ADUser -Filter {(Name -like $search) -and (Enabled -eq $true)}
if ($results) {
'Found {0} users with search {1}' -f @($results).Count, $search
$results | Select Name
}
else {
'No user found with search {0}' -f $search
}
Edit: Updated $input to $usrinput per JS as input is reserved