You can sometimes get away with using curly braces and script block syntax (and this is all over the examples), but the -Filter parameter actually expects a string, and this is the most consistent way of getting it to work. In your case, though, the curly brace syntax would probably also work fine:
Get-ADComputer -Filter { Name -like $computername }
It’s mostly when you need to filter based on object properties (such as Name -like $computer.Name ) where the script block example syntax starts to fall apart.
Thank you so much for your help. I got the -filter variable working based on your suggestions. Now I’ve run into one more problem. At the end when I out my $obj, it outputs fine on screen but when I check the csv file it only contains the last object that $obj held. How do I get it to write everything to the csv?
#Retrieves computer name and serial number and exports it to csv
function Get-ComputerInfo {
param(
$computername = $(Read-Host “Please enter the computer search parameters (ex: bhs72*)”),
$filename = $(Read-Host “Please enter the csv path and filename (ex: c:\test.csv)”)
)
$comps = Get-ADComputer -filter { name -like $computername } | select -ExpandProperty name
foreach ($comp in $comps) {
$os = gwmi win32_operatingsystem -ComputerName $comp
$bios = gwmi win32_bios -ComputerName $comp
You’re exporting to the CSV file inside a loop (and without the -Append parameter, which was added in PowerShell 3.0). Typically, what you’d want to do in PowerShell is have your Get-ComputerInfo function just output objects, and then the caller can choose to pipe that to Export-Csv or whatever they need to do. But if you do choose to create the CSV inside the function, you either need to move the call to Export-Csv outside the loop body (ideally using a ForEach-Object pipeline instead of a foreach loop, so you can pipe the results straight to Export-Csv), or just add the -Append parameter to the Export-Csv call inside the loop.