Powershell Import-CSV Create new row based on a condition

1k views Asked by At

I'm somewhat new to scripting in general. I have a CSV file which I am importing and modifying the data so it presents in a better format.
My question is I want to do (I guess) a foreach loop on all rows of a given column, and if data does not match a certain criteria:

  1. Copy the entire row onto a new row (retaining all other data in the row).
  2. Replace the value of "Column B" with the value of "Column C"

I'm basically doing an import-csv $file. I'll export it later on.

Here is an example: I basically want to move Task2 into the Task1 column IF there is any data present except "--", and then I can ignore the Task 2 column.

Import-csv gives me this:

ID,    TASK1, TASK2
123,    A,     --     
456,    B,     --     
789,    C,     D,     

But I want it to look like this:

ID,   TASK1, TASK2
123,    A ,    --     
456,    B,     --     
789,    C,     D,     
789,    D,     D,                
2

There are 2 answers

3
Esperento57 On BEST ANSWER

Other method:

$data=import-csv "C:\temp\test.txt"
$data + ($data | where TASK2 -ne "--" |  %{$_.TASK1=$_.TASK2;$_})
0
AudioBubble On

For relative small csv files this could be a way ($CSV+= recreates the var each time):

## Q:\Test\2017\09\03\SO_46018965.ps1
$CSV = import-csv 'test.csv'
foreach ($Row in $CSV){
    if ($Row.TASK1 -eq 'C'){
        $NewRow=[PSCustomObject]@{
            ID = $Row.ID
            TASK1 = $Row.TASK2
            TASK2 = $Row.TASK2}
        $CSV+=$NewRow
    }
}
$CSV

Sample output:

ID  TASK1 TASK2
--  ----- -----
123 A     --
456 B     --
789 C     D
789 D     D