I have been asked to create a script to put comma (,) after every word in csv cell using powershell. However the actual csv has not been shared with me due to some security reason.
I have created a test csv and tried to put comma (,) after every word (Screen shot 1). I am able to create the script and it is working 100% fine (Screen shot 2). However the actual file size is approx 250 MB. I am assuming if that file has 100s of columns, do I have to mention each column name in the script as I mentioned in the foreach loop. Is there any easy way to accomplish this task without mentioning each column name. Any help would be appreciated. Below is my script that is working fine:
$csv = Import-Csv -Path C:\temp\test.csv
$outcsv = Read-Host "Enter the name of the output csv"
$outfile = "$env:USERPROFILE\Downloads" "" $outcsv ".csv"
$data = @()
foreach ($item in $csv) {
$col1 = $item.Name ","
$col2 = $item.Location ","
$col3 = $item.Company ","
$col4 = $item.Profile ","
$col5 = $item.Shift ","
$Properties = [ordered]@{
'Name' = $col1
'Location' = $col2
'Company' = $col3
'Profile' = $col4
'Shift' = $col5
}
$data = New-Object -TypeName PSObject -Property $Properties
}
$data | Export-Csv -Path $outfile -NoTypeInformation
Screen shot 2 with comma (,):
CodePudding user response:
This is an easier way to go about it that could handle the logic dynamically by accessing the object's PSObject.Properties
.
$outcsv = Read-Host "Enter the name of the output csv"
if(-not [System.IO.Path]::GetExtension($outcsv)) {
$outcsv = $outcsv '.csv'
}
$outfile = Join-Path "$env:USERPROFILE\Downloads" -ChildPath $outcsv
Import-Csv -Path C:\temp\test.csv | ForEach-Object { $firstObject = $true } {
if($firstObject) {
# get the property names of the first object
$properties = $_.PSObject.Properties.Name
$firstObject = $false
}
# enumerate each property of the object
foreach($property in $properties) {
# update the value
$_.$property = $_.$property ','
}
# output the updated object
$_
} | Export-Csv $outfile