【问题标题】:Powershell writes first line but cannot write subsequent lines to file in for loopPowershell写入第一行但无法将后续行写入for循环中的文件
【发布时间】: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加入?答案就是一切。

标签: powershell file for-loop append write


【解决方案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
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-12
    • 1970-01-01
    • 2020-02-29
    • 1970-01-01
    • 2012-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多