在 PowerShell 中附加文本文件

Chr*_*ass 3 powershell append output

因此,我正在尝试编写一个快速脚本来帮助我儿子学习拼字比赛。我几乎一切正常,但我想跟踪他的结果,所以我尝试将输出写入文本文件。我只关心最近的结果,所以当他开始测试时我删除了现有的结果文件。

我正在为每个人的拼写列表做一个,在每个列表的末尾,我有:

write-host "Word $counter - You spelled $wordcorrectly!!" | Out-File $outputpath -Append
Run Code Online (Sandbox Code Playgroud)

或者

write-host "Word $counter - Sorry.  The correct spelling is $word." | Out-File $outputpath -Append
Run Code Online (Sandbox Code Playgroud)

最后,在浏览完所有列表后,我得到:

write-host "You answered $counter out of $WordCount correctly" | Out-File $outputpath -Append
Run Code Online (Sandbox Code Playgroud)

但是当我转到 $outputpath 文件时,它完全是空白的......猜猜我在这里犯了什么简单的错误?

小智 6

Write-Host ...您正在通过管道传输to的结果Out-File,但Write-Host没有将任何内容传递到管道(它将内容发送到标准输出),因此它Out-File什么也不做(除了覆盖文件)。因此,您可以将字符串本身通过管道传输到它Out-File,它应该可以工作。如果您仍然想 Write-Host 字符串(以查看输出),您可以将消息存储在变量中:

$Message = "You answered $counter out of $WordCount correctly"
Write-Host $Message
$Message | Out-File $outputpath -Append
Run Code Online (Sandbox Code Playgroud)