medlalami
Jul 30, 2023Copper Contributor
Filter CSV file and export
Hi,
I'm doing extraction from a CSV file and filtered data basing on value that exists on an external txt file:
$file1 = 'C:\temp\sourcefile.csv'
$services = Get-Content "C:\Temp\Services.txt"
foreach($service in $services){
$data = Import-Csv -Path $file1 | Where-Object { $_."Service" -eq $service } | Format-Table
}
I would like to export the result on a new CSV file. I tried to do that:
$file2 = "C:\temp\newfile.csv"
$data | Export-Csv -Path $file2 -NoTypeInformation
The file is created but contains wrong data, only strange data.
How can I solve that?
Hi.
You haven't provided example data from either file, meaning all we can do is guess.
I'm assuming the contents of the Services.txt file is simply a list of service names, like:
service 1
service 2I'm assuming the contents of sourcefile.csv is something like:
Service,Status
service 1,running
service 2,stopped# Read the list of services to filter on. $services = Get-Content "C:\Temp\Services.txt"; # Compare the services from the source file to those from the filtering file. Import-Csv -Path 'C:\temp\sourcefile.csv' | Where-Object { $services -contains $_.Service; } | Export-Csv -NoTypeInformation -Path 'C:\temp\sourcefile-filtered.csv';
Cheers,
Lain