Search code examples
csvrowcell

Powershell csv when empty cell - delete row


I have a csv file which has 8 columns. When columns 5 or 6 or 7 or 8 are blank, the whole row need to be deleted.

col1,col2,col3,col4,col5,col6,col7,col8
cont,cont,cont,cont,cont,cont,cont,cont
cont,cont,cont,cont,,cont,cont,cont     --> delete row
cont,cont,cont,cont,cont,cont,,cont     --> delete row
cont,cont,cont,cont,cont,cont,cont,cont

How can I solve this with Powershell?

Thanks in advance.


Solution

  • You will want to do something like this:

    foreach ($line in Get-Content .\myfile.txt) {
       $linearray = $line.split(",");
       if($linearray[4] && $linearray[5] && $linearray[6] & $linearray[7]) {
          Add-Content .\myTempfile.txt $line
       }
    }
    Out-File .\myfile.txt .\myTempFile.txt
    Remove-Item .\myTempFile.txt