在Windows PowerShell中重定向标准输入/输出

102

如何在Windows PowerShell中重定向标准输入/输出?

在Unix上,我们使用:

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

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


1
相关:https://dev59.com/YmQo5IYBdhLWcg3wXuin - eckes
6个回答

122

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

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

12
这行代码会将整个 input.txt 文件读入内存。如果 input.txt 的大小可能很大,请小心。 - Jack O'Connor
4
哪个“cat”?在PowerShell中,“cat”是Get-Content的别名,因此它们是完全相同的东西。 - JasonMArcher
13
不,Get-Content命令逐行读取内容并将其一个接一个地发送到管道中。 - mklement0
1
自PS v1以来就一直是这样。 - JasonMArcher
11
哇,这是一个非常尴尬的做法……如果“<”运算符目前没有被使用,为什么不将其用于大多数人所期望的功能呢 =/ - Jet Blue
显示剩余4条评论

31

如果有人像我一样在寻找大文件的“Get-Content”替代方案,可以在PowerShell中使用CMD:

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

或者您可以使用此 PowerShell 命令:

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

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

编辑:

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

-RedirectStandardOutput

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

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

1
非常感谢!这个 cmd 命令让我能够重定向文件内容,而不会像PowerShell一样在管道中添加新行。 - undefined

10

你可以使用输出重定向来进行:

  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


5
您可以这样做:

或者您可以这样:

$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
    }
}

我发现这种方式可以更好地控制脚本的执行,特别是当你需要处理外部程序/进程时。否则,我曾经遇到过一些脚本因外部进程出错而无法执行的情况。

1

你也可以使用以下方法将标准错误和标准输出发送到同一位置(请注意,在cmd中,2>&1必须是最后的):

get-childitem foo 2>&1 >log

请注意,“>”与“| out-file”相同,默认编码为unicode或utf 16。同时要小心使用“>>”,因为它可能会在同一文本文件中混合ascii和unicode。"| add-content"可能比">>"更好用。"| set-content"可能比">"更可取。

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

我认为你只能将其保存到文本文件中,然后再读入变量。


0
我正在使用PowerShell v7.3.x,并且`Get-Content`已被别名为`cat`。要检查您的PowerShell版本,请运行`Get-Command cat`。
由于`cat`更像是一个shell命令,我会先运行`cat content`,然后使用管道`|`将输入重定向到我们想要的`exe`。
要么使用绝对路径,要么在目录中调用。
PS C:\user\working-dir > cat .\input | .\program.exe 

附上屏幕截图 屏幕截图

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接