2

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!

8
  • If you remove the Pause or hit Enter do you see the output? You might be falling foul of an issue where output (implicitly) send to Format-Table is delayed for 300ms and is being blocked by the Pause - see stackoverflow.com/a/59331305/3156906 for more details... Commented Feb 8, 2023 at 20:59
  • Your Where-Object clause is using an undefined variable $filter, not $UName... Commented Feb 8, 2023 at 21:07
  • @Theo - Corrected... In my actual script I had it correct. I have updated this post. Commented Feb 8, 2023 at 21:16
  • @mclayton - If I remove the Pause or hit Enter it just goes to PS C:\Users\UserName\Documents> Commented Feb 8, 2023 at 21:18
  • Why not use the Active Directory filter instead of Where-Object ? Commented Feb 8, 2023 at 21:18

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

THANK YOU!!!! after 9 years out of scripting I would have never thought of this solution!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.