【问题标题】:How to get the heading like this using powershell如何使用powershell获取这样的标题
【发布时间】:2021-02-20 19:55:54
【问题描述】:

我想将标题作为"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

提前致谢!

【问题讨论】:

  • 请也包含您的代码
  • 请在此处发布时尽量避免代码/数据/错误的图像。为什么? lookee ...为什么在提问时不上传代码/错误的图像? - 元堆栈溢出 — meta.stackoverflow.com/questions/285551/…
  • 你尝试过这样的事情吗:Export-Csv -Path .\whatever.csv -Delimiter '|'

标签: powershell scripting cmdlets


【解决方案1】:

虽然我不太确定您打算做什么,但对我来说,问题是 “我有管道分隔的数据,但缺少的只是标题行”
如果是这样的话,你可以做一些简单的事情:

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

【讨论】:

    【解决方案2】:

    语法不正确... 就这样吧……

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

    【讨论】:

      猜你喜欢
      • 2021-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-04
      • 2021-08-27
      • 2021-05-23
      相关资源
      最近更新 更多