Forum Discussion

medlalami's avatar
medlalami
Copper Contributor
Jul 30, 2023
Solved

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" ...
  • LainRobertson's avatar
    Jul 31, 2023

    medlalami 

     

    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 2

     

    I'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

Resources