【问题标题】:Redirecting standard input\output in Windows PowerShell在 Windows PowerShell 中重定向标准输入\输出
【发布时间】:2012-07-11 22:52:38
【问题描述】:

在 Windows PowerShell 上重定向标准输入/输出所需的语法是什么?

在 Unix 上,我们使用:

$./program <input.txt >output.txt

如何在 PowerShell 中执行相同的任务?

【问题讨论】:

标签: powershell powershell-2.0 stdin


【解决方案1】:

您不能将文件直接挂钩到标准输入,但您仍然可以访问标准输入。

Get-Content input.txt | ./program > output.txt

【讨论】:

  • 这会将整个input.txt 文件读入内存。如果input.txt 可能很大,请小心。
  • 哪个cat?在 PowerShell 中,“cat”是Get-Content 的别名,所以它们完全一样。
  • @JackO'Connor:不,Get-Content 通过管道一个接一个发送它读取的行。
  • 从 PS v1 开始就是这样。
  • 哇,这是一种多么尴尬的方式...
【解决方案2】:

如果有人(如我)正在寻找大文件的“获取内容”替代方案,您可以在 PowerShell 中使用 CMD:

cmd.exe /c ".\program < .\input.txt"

或者你可以使用这个 PowerShell 命令:

Start-Process .\program.exe -RedirectStandardInput .\input.txt -NoNewWindow -Wait

它将在同一窗口中同步运行程序。但是当我在 PowerShell 脚本中运行它时,我无法找到如何将这个命令的结果写入变量,因为它总是将数据写入控制台。

编辑:

要从 Start-Process 获取输出,您可以使用选项

-重定向标准输出

用于将输出重定向到文件,然后从文件中读取:

Start-Process ".\program.exe" -RedirectStandardInput ".\input.txt" -RedirectStandardOutput ".\temp.txt" -NoNewWindow -Wait
$Result = Get-Content ".\temp.txt"

【讨论】:

    【解决方案3】:

    对于输出重定向,您可以使用:

      command >  filename      Redirect command output to a file (overwrite)
    
      command >> filename      APPEND into a file
    
      command 2> filename      Redirect Errors 
    

    输入重定向以不同的方式工作。例如看这个 Cmdlet http://technet.microsoft.com/en-us/library/ee176843.aspx

    【讨论】:

      【解决方案4】:

      或者你可以这样做:

      类似:

      $proc = Start-Process "my.exe" "exe commandline arguments" -PassThru -wait -NoNewWindow -RedirectStandardError "path to error file" -redirectstandardinput "path to a file from where input comes"
      

      如果您想知道进程是否出错,请添加以下代码:

      $exitCode = $proc.get_ExitCode()

      if ($exitCode){
          $errItem = Get-Item "path to error file"
          if ($errItem.length -gt 0){
              $errors = Get-Content "path to error file" | Out-String
          }
      }
      

      我发现,当您需要处理外部程序/进程时,我确实可以更好地处理脚本的执行。否则我会遇到脚本会因某些外部进程错误而挂起的情况。

      【讨论】:

        【解决方案5】:

        你也可以这样做让标准错误和标准输出到同一个地方:

        get-childitem foo 2>&1 >log

        注意“>”和“| out-file”是一样的,默认编码是unicode或utf 16。还要小心“>>”,因为它可以在同一个文本中混合ascii和unicode文件。 "| add-content" 可能比 ">>" 效果更好。 "| set-content" 可能比 ">" 更可取。

        现在有 6 个流。更多信息:https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_redirection?view=powershell-5.1

        我认为你所能做的就是保存到一个文本文件,然后将它读入一个变量。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-05-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多