0

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.

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.