I tried to use the most of Import-CSV , so i write this script import-csv.ps1
I know it looks like a puzle, but at least i did my best effort.
There should be a better way and shorter than this, i hope if we can make it to work with any CSV-file, because realy i did not try with other CSV-files, and many thanks for your support.
Note: the ouput of header line comes as sorted, where it should not be like that.
# import-csv.ps1
#
# read from CSV file-format,
# and write to CSV file-format by sorted header-Names
#
clear-host
set-psdebug -strict
$readFile = "test01.csv"
$arrayLines = @()
# read from CSV file-format
$arrayLines = import-csv $readFile
$arrayLines[0] |
get-member -MemberType NoteProperty |
select-object name |
forEach-object `
-begin {
$arrayHeader = @()
$strHeader = ""
} `
-process {
$arrayHeader += $_.name
$strHeader += $_.name + ","
} `
-end {
$outFile = `
$readFile.substring(0, `
$readFile.lastindexofany(".")) + ".out"
# save header-line to CSV output-file
out-file -filePath $outFile `
-inputObject $strHeader -encoding ASCII -force
}
for ($indx = 0; $indx -le $arrayLines.length-1; $indx += 1)
{
$records = ""
for ($rec = 0; $rec -le $arrayHeader.length-1; $rec += 1)
{
$records += $arrayLines[$indx].($arrayHeader[$rec]) + ","
}
# add the records to CSV output-file
out-file -filePath $outFile `
-inputObject $records -encoding ASCII -append
}
break
#-----------------------------------------------------
input CSV-file test01.csv :
No.,Fname,ID Name,Date,start,finish
1,Bank Hes,BAH,10/09/2008,09:24:01,12:20:56
2,Iran Abe,IRA,01/09/2008,16:14:14,19:24:17
3,Dara Man,DAM,10/09/2008,16:15:47,23:06:33
output-file test01.out:
Date,finish,Fname,ID Name,No.,start,
10/09/2008,12:20:56,Bank Hes,BAH,1,09:24:01,
01/09/2008,19:24:17,Iran Abe,IRA,2,16:14:14,
10/09/2008,23:06:33,Dara Man,DAM,3,16:15:47,