2
votes

I have a problem with my code, when I export in the file only one object is displayed in the file, an example should be better:

There is the result :

Field1
Test1

And I want to get this :

Field1  col1    col2   Field2   col3   col4
Test1   a       b      Test2     c      d
        a2      b2               c2     d2

The file :

col1    col2
a       b
a2      b2

I've tried my best to produce a piece of code, hope this will help. I create the field in the code.

$csv = Import-Csv .\file.csv -Delimiter ';'
$dataTable = New-Object System.Data.DataTable

$dataTable.Columns.Add("Field1") | Out-Null


foreach ($s in "Test1")
{
  $row = $dataTable.NewRow()

  $row["Field1"] = $s

  $dataTable.Rows.Add($row)
}

#my problem is there, I don't know how merge these two lines
$dataTable | export-csv -NoTypeInformation -Path ".\fileResult.csv"

$csv | Export-CSV   -Path ".\fileResult.csv" -NoTypeInformation -Delimiter ";" -Append
1
You're only adding one column to the table... Do you not need to add the others too?arco444
Sry, I didn't show all the expected file but my problem is in the title. I have two lines and I don't know how to merge that to get the result at the top. Or maybe it's not called object ?Teslo

1 Answers

2
votes

In you example, you have headings and one row. I assume you would line to loop over multiple rows.

Running all of this code will give you errors; either use the single-line or looping version.

$csv = Import-Csv .\file.csv -Delimiter ';'

#Single line
$csv | Add-Member -Type Noteproperty -Name "Field1" -Value "Test1"
$csv | Add-Member -Type Noteproperty -Name "Field2" -Value "Test2"

#looping over all lines
foreach($line in $csv({
    $line | Add-Member -Type Noteproperty -Name "Field1" -Value "Test1"
    $line | Add-Member -Type Noteproperty -Name "Field2" -Value "Test2"
}

# use Select-Object to get orders CSV
$csv | Select-Object Field1, col1, col2, Field2 | Export-CSV   -Path ".\fileResult.csv" -NoTypeInformation -Delimiter ";" -Append

Edit: some explanation

Your CSV file is imported as an object. The headings (col1, col2) are automatically assigned as NoteProperty members of the object. You can see this by running $csv | Get-Member.

You can add members to the CSV object using Add-Member, specifying the member type, Name (heading) and value.

Documentation

Import-Csv
Add-Member
Export-Csv
Select-Object