【问题标题】:How to redirect output?如何重定向输出?
【发布时间】:2012-03-20 22:25:19
【问题描述】:

我正在尝试将 Powershell 脚本的输出重定向到 txt 文件。

在 Powershell 窗口中,我尝试:

.\script.ps1 > list.txt

但这无济于事,所有输出仍会打印到窗口。

然后我尝试了:

.\script.ps1 >& list.txt

得到了这个错误:

Missing file specification after redirection operator.
At line:1 char:21
+ .\script.ps1 > <<<< & list.txt
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : MissingFileSpecification

【问题讨论】:

    标签: powershell io windows-xp


    【解决方案1】:

    如果您使用Write-Host(或[Console]::WriteLine)在script.ps1 中编写输出,则需要将其更改为Write-Output 或执行以下操作:

    powershell.exe -File test.ps1 > out.txt
    

    顺便说一句,&gt;Out-File 的语法糖,它们是同一个东西。

    【讨论】:

    • 现在我得到:“重定向运算符后缺少文件规范。”我尝试了很多我能想到的变体:(
    【解决方案2】:

    如果您要捕获的输出正在使用 Write-Host 写入控制台,则需要将其更改为 Write-Output。

    【讨论】:

    • 脚本使用[Console]::WriteLine
    • @JBurace [Console]::WriteLineWrite-Host 基本上是一回事。 [Console]::WriteWrite-Host -NoNewLine
    【解决方案3】:

    &gt; 之后不需要&amp;。它仅用于执行某些操作。

    .\script.ps1 > list.txt
    

    如果script.ps1 使用Write-Host[Console]::WriteLine 输出,则需要更新它。

    Here 是将Write-Host 脚本更新为可输出的示例。

    【讨论】:

    • 您的意思可能是Write-HostWrite-Output&gt; list.txt 配合得很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-04
    • 2010-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多