1

I'm trying to use Get-ADComputer in Powershell to search using variables when I know part of the computer name.

If I only use a string with quotes, it works great:

Get-ADComputer -Filter {Name -Like "*mputername*"} | Select Name

If I create a string variable and THEN do the same search using the variable, it doesn't return anything. I think it has something to do with how the variable is being expanded next to the wildcard asterisks, but I'm stumped.

Set-Variable -Name 'partialName' -Value 'mputername'

Get-ADComputer -Filter {Name -Like "*$partialName*"} | Select Name

Can anyone help me?

puterguy01
  • 135
  • 1
  • 10
  • 1
    `$nameFilter = "*mputername*"; Get-ADComputer -Filter {Name -like $nameFilter}` should work. – Mathias R. Jessen Oct 21 '22 at 15:28
  • 1
    While the ADCmdlets can technically take scriptblocks as filters, it's generally better to use strings for them: `Get-ADComputer -Filter "Name -like '$namefilter'"`. – Jeff Zeitlin Oct 21 '22 at 15:36
  • 1
    To add to the two helpful comments: the linked duplicate explains solution options and also why using script blocks (`{ ... }`) is best avoided for conceptual reasons. – mklement0 Oct 21 '22 at 15:42
  • Glad to hear it, @puterguy01. – mklement0 Oct 21 '22 at 16:21

0 Answers0