Search code examples
powershellscriptingpowershell-cmdlet

How to get the heading like this using powershell


I want to get the heading as "StudentID|studentfirstname|studentlastname|class" to my existing data as below:

2|vicky|kash|A
5|abc|sdf|B
9|sdf|sdf|D

My code looks like:

add-content -path "outfile.txt" -Value  (-join($StudentID, "|",`
$studentfirstname, "|",` $studentlastname, "|",`$class)

Expected output file:

StudentID|studentfirstname|studentlastname|class
2|vicky|kash|A
5|abc|sdf|B
9|sdf|sdf|D

Thanks in Advance!


Solution

  • Although I'm not quite sure what you intend to do, but to me the question reads as "I have pipe-delimited data and all it is missing is a header line".
    If that is the case, you coud do something as simple as:

    $fileIn  = 'D:\Test\YourFile.csv'
    $fileOut = 'D:\Test\YourFile2.csv'
    # write the header line to a new file
    Set-Content -Path $fileOut -Value "StudentID|studentfirstname|studentlastname|class"
    # read the original file and append it to the one you have just created
    Get-Content -Path $fileIn -Raw | Add-Content -Path $fileOut
    

    If your input file is really large, below a faster alternative:

    $fileIn  = 'D:\Test\YourFile.csv' 
    $fileOut = 'D:\Test\YourFile2.csv'
    # write the header line to a new file
    Set-Content -Path $fileOut -Value "StudentID|studentfirstname|studentlastname|class"
    # read the original file and append it to the one you have just created
    [System.IO.File]::AppendAllText($fileOut, ([System.IO.File]::ReadAllText($fileIn)))