Jonathan-Ball
Jonathan-Ball

Reputation: 5

Powershell - Add data from one CSV into new column and rows of another CSV file

I am trying to add data from one CSV file into another CSV file with Powershell

Expected output Example:

Network, Agent
Net1, Agent1
Net2, Agent2

Currently I am only managing to add the data like this which defeats the point:

Network
Net1
Net2
Agent
Agent1
Agent2

The reason for this is my program will need to specify the agents in an already generated CSV file.

Could anybody advise how I can add an additional column and then fill the data in the next rows?

Many thanks.

Upvotes: 0

Views: 640

Answers (1)

AdminOfThings
AdminOfThings

Reputation: 25021

If both CSV files have the same number of data rows, you can use Import-Csv and calculated properties. Then loop through each data row simultaneously.

$network = Import-Csv network.csv
$agent = Import-Csv agent.csv
0..($network.Count-1) |
    Select @{n='Network';e={$network[$_].Network}},@{n='Agent';e={$agent[$_].Agent}} |
        Export-Csv output.csv -NoType

$_ is the current object in the pipeline, which iterates through all of the objects.


If you want to add a new property to an existing custom object, you can still use calculated properties.

Import-Csv network.csv | Foreach-Object {
    $agent = 'Agent Value' # some code to get the agent
    $_ | Select-Object Network,@{n='Agent';e={$agent}}
} | Export-Csv output.csv -NoType

Upvotes: 1

Related Questions