如何使用powershell获得这样的标题

How to get the heading like this using powershell

我想将标题设为 "StudentID|studentfirstname|studentlastname|class" 到我现有的数据中,如下所示:

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

我的代码如下:

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

预期输出文件:

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

提前致谢!

语法不正确... 就这样做...

$StudentID        = '123'
$studentfirstname = 'John'
$studentlastname  = 'Doe'
$class            = 'Math'


Clear-Host
"$StudentID|$studentfirstname|$studentlastname|$class"
# Results
<#
123|John|Doe|Math
#>

或者

Clear-Host
$StudentID,$studentfirstname,$studentlastname,$class -join '|'
# Results
<#
123|John|Doe|Math
#>

或者

Clear-Host
"{0}|{1}|{2}|{3}" -f $StudentID,$studentfirstname,$studentlastname,$class
# Results
<#
123|John|Doe|Math
#>

虽然我不太确定你打算做什么,但对我来说问题是 “我有 pipe-delimited 数据,但缺少的只是一个 header 行".
如果是这种情况,您可以做一些简单的事情:

$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

如果您的输入文件确实大,下面是一个更快的替代方案:

$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)))