Reputation: 31
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
Upvotes: 2
Views: 5528
Reputation: 10019
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
Upvotes: 2