powershellpowershell-3.0powershell-4.0powershell-core

How to delete all lines AFTER and INCLUDING a certain string?


I have a need to delete all lines in a csv AFTER and INCLUDING a certain string. The string is as follows :

S_Channel_Alt_View

enter image description here

The file should then look like this

enter image description here

I've tried to set something up using Compare-Object but unable to get it to work.

Thank you!


Solution

  • it's a simple matter of loading the original CSV then looping through it and stop once you find the wanted value

    $CsvContent = Import-Csv -Path 'c:\path\to\your\csv.csv'
    $ColumnName = 'Custom2'
    $FilterValue = 'S_Channel_Alt_View'
    
    $FilteredContent = foreach ($Line in $CsvContent) {
        $Line
        if ($Line.$ColumnName -like $FilterValue ) { break }
    }
    $FilteredContent | Export-Csv -Path 'c:\path\to\your\csv_2.csv'