I have tried the "filter" and "param" options from the post
-- In powershell passing variable to where-object not working -- with no luck. I am fairly new to powershell since I have not used it since 2014. Can anyone assist me in finding out why the $UName
variable is not being passed to the Where-Object
command?
cls
$UName = Read-Host -Prompt "Name or part of name to search"
Write-Output "Searching for: $UName, please wait"
Get-ADUser -Filter * -Properties * | Where-Object {
$_.name -like "*$UName*" -and
$_.company -like "*XYZ Corp*"
} | select Name, title, company, Country, mailnickname
Pause
My only output is:
Name or part of name to search: Justin
Searching for: Justin, please wait
Press Enter to continue...
I have even tried using -Contains $UName
and -Contains "$UName"
yet still get the same results as above.
I have searched, and searched but cannot figure this out. Any assistance would really help!
Your script can be simplified as follows, you really shouldn't query all Domain Users (-Filter *
) to then filter them with PowerShell (Where-Object
). Instead, you should use the Active Directory Filter. Same goes for querying all users properties (-Properties *
) when you actually only need some of them (Name, title, company, Country, mailnickname
).
# using Trim() to remove any excess whitespace (trailing and leading)
$UName = (Read-Host -Prompt "Name or part of name to search").Trim()
# if there was no input or input was purely whitespace
if(-not $UName) {
# exit this script
return
}
# if input was valid
Write-Output "Searching for: $UName, please wait"
# try to search for the user
$props = 'Name', 'title', 'company', 'Country', 'mailnickname'
Get-ADUser -LDAPFilter "(&(name=*$UName*)(company=*XYZ Corp*))" -Properties $props |
Select-Object $props | Format-Table -AutoSize