【问题标题】:Exporting powershell output to text file将 powershell 输出导出到文本文件
【发布时间】:2012-04-26 19:24:07
【问题描述】:

我的 powershell 脚本中有一个 foreach 循环,每次迭代期间都会在 shell 上打印 $output。有很多输出,shell 可以显示的条目数量是有限的。我希望将输出导出到文本文件。我知道如何在命令行中执行此操作。但是在powershell中怎么可能呢?

仅供参考,我正在使用命令行中的批处理脚本来运行 powershell 脚本

powershell c:\test.ps1 c:\log.log 

【问题讨论】:

    标签: windows powershell command-line scripting batch-file


    【解决方案1】:

    您始终可以将输出的 exe 重定向到这样的文件(即使来自 cmd.exe):

    powershell c:\test.ps1 > c:\test.log
    

    在 PowerShell 中,您还可以将单个命令重定向到文件,但在这些情况下,您可能希望附加到日志文件而不是覆盖它,例如:

    $logFile = 'c:\temp\test.log'
    "Executing script $($MyInvocation.MyCommand.Path)" > $logFile
    foreach ($proc in Get-Process) {
        $proc.Name >> $logFile
    }
    "Another log message here" >> $logFile
    

    如您所见,在脚本中进行重定向有点麻烦,因为您必须对文件进行大量重定向。 OTOH,如果您只想将部分输出重定向到文件,那么您可以通过这种方式进行更多控制。另一种选择是使用Write-Host 将信息输出到控制台,以供观察脚本执行结果的人使用。请注意,Write-Host 输出无法重定向到文件。

    这是一个从 CMD.exe 执行的示例

    C:\Temp>type test.ps1
    $OFS = ', '
    "Output from $($MyInvocation.MyCommand.Path). Args are: $args"
    
    C:\Temp>powershell.exe -file test.ps1 1 2 a b > test.log
    
    C:\Temp>type test.log
    Setting environment for using Microsoft Visual Studio 2008 Beta2 x64 tools.
    Output from C:\Temp\test.ps1. Args are: 1, 2, a, b
    

    【讨论】:

    • 因此,如果我对 powershell 脚本有一个参数,我可以简单地执行以下操作:powershell c:\test.ps1 c:\log.log > c:\test.log where log.log是论据吗?
    • 是的,但请尝试使用 -File 参数,例如powershell -file c:\test.ps1 c:\log.log > c:\test.log
    • 如果我尝试在批处理文件中使用文件参数(或不使用文件),我会在命令行中执行以下行:powershell -file c:\test.ps1 c:\log.log 1>c:\test.log 我不明白“1”是如何出现的.....而且我猜脚本名称之后的整个文本都被视为输入文件名,因此输出不是预期的.无论我是否使用“-file”,这种行为都是一样的。
    • @ssn 我不确定你为什么看到1>。我更新了答案以显示这对我来说是如何工作的。
    【解决方案2】:

    使用 'tee' 命令怎么样

    C:\ipconfig | tee C:\log.txt
    

    【讨论】:

    • 这就是我要找的。我想输出到屏幕和文件。谢谢!