Powershell写入第一行但无法将后续行写入for循环中的文件

Posted

技术标签:

【中文标题】Powershell写入第一行但无法将后续行写入for循环中的文件【英文标题】:Powershell writes first line but cannot write subsequent lines to file in for loop 【发布时间】:2021-09-24 21:59:08 【问题描述】:

我有一个嵌套的for 循环,我试图在其中将一个新的line 文本写入最内层循环内的[csv] 文件。

在我的一生中,我无法让它发挥作用。它写了第一行,但没有别的。 Powershell 尽职尽责地将每一行文本写入控制台,但无论我选择哪种文件写入方法,我都只是 REFUSES 在第一行之后附加 anything else ($headers) .

我做错了什么?

$blob = "a 1 b 2 c 3 d 4 e 5"
$outfile = 'C:\myfile.txt'
$arr = @('1','2','3','4','5')

# try with Out-File -- FAILS
ForEach ($num in $arr) 
    If ($blob -match "(?<name>[^\s]) (?<num>$([regex]::Escape($num)))") 
        Write-Host $Matches.name $Matches.num -Separator "," |
        Out-File -Encoding ascii -FilePath "$outfile" -Append -Force
    


# try with Add-Content -- FAILS
ForEach ($num in $arr) 
    If ($blob -match "(?<name>[^\s]) (?<num>$([regex]::Escape($num)))") 
        Write-Host $Matches.name $Matches.num -Separator "," |
        Add-Content -Encoding Ascii "$outfile"
    


# try with Export-Csv -- FAILS
ForEach ($num in $arr) 
    If ($blob -match "(?<name>[^\s]) (?<num>$([regex]::Escape($num)))") 
        Write-Host $Matches.name $Matches.num -Separator "," |
        Export-Csv -Encoding ASCII -Force -Append -LiteralPath "$outfile"
    

自创建文件以来,我拥有文件的完全写入权限。 我不认为这是数据类型冲突(真正的代码只处理字符串)。

这让我发疯了!

特别煽动性 是,如果我复制单个内部循环行并手动执行它(而 $vars 仍在内存中),它会附加到文件>8O!

Write-Host $Matches.name $Matches.num -Separator "," | Out-File -Encoding ascii -FilePath "$outfile" -Append -Force

可能是什么问题?

非常感谢任何帮助。

【问题讨论】:

这些 cmdlet 都不能捕获Write-Host 的输出,该输出会进入信息流而不是标准输出。首先,删除Write-Host 并尝试,看看是否有效。 @SantiagoSquarzon 好的,谢谢,但在我的真实脚本中,我想利用Write-Host-Separator 参数来创建TAB 分隔字符串。我会尝试您的建议并报告。 您可以使用-join "`t"将字符串与制表符连接起来。 我可以使用-join 加入多少个不同的字符串对象? 你的意思是你的数组中有多少元素可以用tab加入?答案就是一切。 【参考方案1】:

根据@SantiagoSquarzon 的建议,这很有效:

$blob = "a 1 b 2 c 3 d 4 e 5"
$outfile = 'C:\myfile.txt'
$arr = @('1','2','3','4','5')

# try with Out-File -- FAILS
ForEach ($num in $arr) 
    If ($blob -match "(?<name>[^\s]) (?<num>$([regex]::Escape($num)))") 
        $Matches.name, $Matches.num, -Separator "," |
        Out-File -Encoding ascii -FilePath "$outfile" -Append -Force
    

【讨论】:

以上是关于Powershell写入第一行但无法将后续行写入for循环中的文件的主要内容,如果未能解决你的问题,请参考以下文章

delphi中怎么逐行读取文本文件的数据并将每行分别写入指定的不同编辑框

powershell Powershell脚本,用于根据匹配的表达式从文本文件中增加一行中的数字,然后将其写入文件。

2018-10-23 sed在文件首行写入内容

VB 写入文件写入特定一行

如何将文本文件的第一行放在结束位置

从提取的 JSON 数据中追加和/或写入 CSV