【问题标题】:Redirect the output of a PowerShell script to a file using command prompt使用命令提示符将 PowerShell 脚本的输出重定向到文件
【发布时间】:2019-07-11 23:53:30
【问题描述】:

如何在 Windows 10 中使用 cmd 将 PowerShell 5.0 脚本的输出重定向到文件?我尝试了以下方法:

powershell ".\myscript.ps1 | Out-File outfile.txt"

和:

powershell .\myscript.ps1 > outfile.txt

无济于事。 outfile.txt 已创建但仍为空。命令提示符窗口以管理员权限运行。

在我使用的脚本中:

Write-Host $MyVar
Write-Host $SomeOtherVar

将值输出到屏幕。

【问题讨论】:

  • 我不是专家,但不是没有-Command选项吗?
  • 你的 .ps1 输出了什么?
  • @I.TDelinquent 一些内部信息。它按原样运行时按预期工作,并按预期在 powershell 控制台中显示输出。我想将此输出重定向到使用 cmd 的文件。
  • @Ron myscript.ps1 使用 Write-Host 吗?在任何情况下都不会被重定向
  • @MathiasR.Jessen 确实如此。

标签: powershell cmd


【解决方案1】:

使用特定的PowerShell redirection operators:
(它们似乎也可以在 (cmd) 命令提示符下工作)

重定向成功流 (1>):

powershell .\myscript.ps1 1> outfile.txt

重定向所有流 (*>):

powershell .\myscript.ps1 *> outfile.txt

【讨论】:

    【解决方案2】:

    在我使用的脚本中:

    Write-Host $MyVar
    Write-Host $SomeOtherVar
    

    将值输出到屏幕。

    是的,这就是你的问题! Write-Host 将信息直接写入主机应用程序的屏幕缓冲区,因此标准输出流将永远看不到任何内容。

    将您的 Write-Host 语句更改为 Write-Output(或删除它们):

    Write-Output $MyVar
    Write-Output $SomeOtherVar
    # or simply
    $MyVar
    $SomeOtherVar
    

    【讨论】:

      猜你喜欢
      • 2012-12-25
      • 2022-01-24
      • 1970-01-01
      • 2010-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多