问题描述
我想以"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,$class
# Results
<#
123|John|Doe|Math
#>
,
虽然我不太确定您打算做什么,但是对我来说,问题是“我有竖线分隔的数据,而缺少的只是标题行”。 /> 在这种情况下,您可以做一些简单的事情:
$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)))