powershellcsvfiltertxtimport-from-csv

Powershell import csv where column data matches data in txt file


I have a csv file that has header called CompanyName. In the csv there are tons of rows and different company names. But I keep a text file with specific companies whose data I need to retrieve. Through PowerShell is there a way to make the Where-Object check through a txt file. Something like:

Import-Csv -Path myCSV | Where-Object { $_.'CompanyName' -in names.txt}

The above doesn't actually work. I even put the names from the text file into an array and tried checking like that but it also doesn't work.

$arr = [string[]]$arrayFromFile = Get-Content -Path "names.txt"
Import-Csv -Path myCSV | Where-Object {$_.'CompanyName' -in $arr  }

Solution

  • Your code worked for me, just needed a small edit in the Get-Content part.

    There's no need to convert to string array, but if you wanted to be specific about the type that's fine.

    It should look like this-

    [string[]]$arr = Get-Content -Path "names.txt"
    

    Whole thing without the type conversion. You'll need names.txt and mycsv.csv in the folder, or to use the full path.

    $arr = Get-Content -Path "names.txt"
    
    Import-Csv -Path "myCSV.csv" | Where-Object {$_.CompanyName -in $arr  }