Link to home
Start Free TrialLog in
Avatar of motioneye
motioneyeFlag for Singapore

asked on

Powershell to add extra column when doing re-order of column field

Hi all,
I have following powershell script that I use to re-order column, its actually works pretty fine and fast.  There is  few changes that I need to work on this scripts.

1: How do I introduce new column in output file although existing file did not have those column ? I need to add two more column between $data[4], $data[7], $data[6], I also need to add column name header in this new column  since the rest of the column has column header.




$ImportFile="DWH_Import_File.csv"
$ImportDate = (Get-Date).AddDays(-1).ToString('yyyy-MM-dd')
$DWHFile = "DWH_Import_File_$ImportDate"
$DWHFile1 ="$ImportFile-Convert.csv"
$Import = [System.IO.File]::OpenText("F:\DWH\HRISEMP\$ImportFile")
$DWHdata = New-Object System.IO.StreamWriter "F:\DWH\HRISEMP\Tool\$DWHFile1"
for(;;) {
    $line = $Import.ReadLine()
    if ($null -eq $line) {
        break
    }
    $data = $line.Split(",")
    $DWHdata.WriteLine('{0},{1},{2},{3},{4},{5},{6},{7},{8}', $data[0], $data[8], $data[5], $data[4], $data[7], $data[6], $data[2], $data[1], $data[3])
}

$Import.Close()
$DWHdata.Close()

Open in new window

Avatar of Norie
Norie

It's not 100% clear where you want the new columns but this will add a new column named NewCol1 between $data[4] and $data[7] and a new column named NewCol2 between $data[7], $data[6].

for(;;) {
    $line = $Import.ReadLine()
    if ($null -eq $line) {
        break
    }
    $data = $line.Split(",")
    $DWHdata.WriteLine('{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10}', $data[0], $data[8], $data[5], $data[4],'NewCol1',  $data[7],'NewCol2', $data[6], $data[2], $data[1], $data[3])
}

$Import.Close()
$DWHdata.Close()

Open in new window

SOLUTION
Avatar of motioneye
motioneye
Flag of Singapore image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of motioneye

ASKER

Thanks Norie :)