Home > Blockchain >  Issues getting get-adcomputer to recognize variable in filter
Issues getting get-adcomputer to recognize variable in filter

Time:10-20

Below is the code I am working with. I have verified that the initial import-csv is working as it should be, and if I change out the variable object for a concrete object, the script works as it should. It just seems to not recognize/use the variable the way that it should.

$CSVOutput = "C:\temp\output.csv"
   $Output = foreach($u in $userlastname)
   {
       Get-ADComputer -Filter {Description -Like '*$u*'} -properties Description | Select Name, Description
   }
$Output | Export-Csv $CSVOutput

If I replace the $u in the filter with one of the values from the $userlastname variable, it works, but it just runs the search with the set value as many times as it runs the foreach loop. I am expecting to see several different computer objects that have the different values from $userlastname in their description. Currently it returns nothing, as if it found no values that matched in the description field.

CodePudding user response:

While it’s technically possible to use a scriptblock as a filter in the ADCommands, it isn’t recommended - use a string instead:

Get-ADComputer -Filter "Description -like '*$($u.name)*'" -Properties ...

Using a string will solve your variable substitution issue.

ETA: Comments indicated that you were getting @{Name=User} as the expansion for $u in the filter expression. This is because $u was a structured [PSCustomObject], and you were looking for a single field from that object. The easiest way to get the value of the desired field of the object is simply to use the PowerShell evaluation construct, as given in the edited answer.

  • Related