Hi everyone! I'm trying to write a PowerShell script that takes a list of last names from a CSV file and queries the description field of AD computer objects for any matches. The catch is that the description field has additional information, so I need to use the -like operator to find partial matches. I've struggled with this for a while now, and I've only been able to get it to work if I manually specify the name like this: `get-adcomputer -filter * -properties Description | where Description -like '*John*'`. What I really want is to automate this to pull names directly from the CSV and output a new CSV file containing the matched computer names. Here's the script I've been trying to get to work:
```powershell
$import = import-csv "U:tempnames.csv"
$computers = foreach ($computer in $import){
get-adcomputer -filter * -properties description | where description -like "*$computer.Name*"
}
$computers | Select name,description | Export-CSV -Path U:Tempmatched_computers.csv -NoTypeInformation
```
4 Answers
The script you provided is too complex for what you need. I suggest simplifying it. Start by running your matches and then focus on outputting the results correctly without over-complicating the CSV outputs until you're sure of the matches.
Instead of querying every computer and then filtering, you should filter by description right at the beginning. This is done on the domain controller (DC) and saves you a lot of time. Try using this command: `get-adcomputer -filter 'description -like "*john*"'` to make it much faster!
Thanks for the advice! I updated my script to reflect that.
Here’s something that might help: You could do this with a loop like this:
```powershell
Import-Csv -Path C:Tempmy.csv | ForEach-Object -Process {
$row = $_
Get-ADComputer -Filter * -Properties Description | Where-Object -FilterScript { $_.Description -match $row.Description }
}
```
Just a note—although filtering left is generally faster, for most applications, the performance difference is not critical. If you're looking to create a full output of matched computer names along with the descriptions, you might want to refine it further.
That’s a solid solution! Just a suggestion: try to move the `Get-ADComputer` command outside of your loop to avoid pulling all computers with every iteration.
You might want to build your filter using string formatting. For instance, `('''*{0}*''' -f $adUser.lastName)` can help. Keep in mind that -in and -contains won’t allow partial matches, but you could use -match for regex, which would work well if you want to avoid doing loops.
That's a neat trick! I tried it out, and now I can see the matches coming through. Thanks!
I appreciate the feedback! I’ve gone back to simplify things and will see how that goes.