Fiddle Freak
Fiddle Freak

Reputation: 2041

Insert new column with value in CSV file, based on value from a column already there

I'm trying to read a value from an object in a CSV File (Using PowerShell 3.0). Based on what that value is, I will create a new column and insert a value (in the same row).

For example, I have the CSV file:

Attribute1,Attribute2
Valuea1,Valueb1
Valueb1,Valuea1
Valuea1,Valueb1
Valueb2,Valuea2
Valuea2,Valueb2

For each "Valueb1" in Attribute2 insert a value "Found" into a new column Data. So in the end, it should look like this (notice just the added , if there is no "Found"):

Attribute1,Attribute2,Data
Valuea1,Valueb1,Found
Valueb1,Valuea1,
Valuea1,Valueb1,Found
Valueb2,Valuea2,
Valuea2,Valueb2,

I'm not familiar with how nested loops work with objects in CSV files using PowerShell.

Upvotes: 0

Views: 1185

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200373

Add a calculated property with a value depending on the value of Attribute2:

Import-Csv 'C:\input.csv' |
  Select-Object -Property *,
    @{n='Data';e={if ($_.Attribute2 -eq 'Valueb1') {'Found'} else {''}}} |
  Export-Csv 'C:\output.csv' -NoType

Upvotes: 3

Related Questions