如何使用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,$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)))

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...