首页 文章

将powershell输出导出到文本文件

提问于
浏览
5

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

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

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

2 回答

  • 12

    您始终可以将输出和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
    
  • 4

    怎么样使用'tee'命令

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

相关问题