如何在Windows PowerShell中重定向标准输入/输出?
在Unix上,我们使用:
$./program <input.txt >output.txt
我该如何在PowerShell中执行相同的任务?
如何在Windows PowerShell中重定向标准输入/输出?
在Unix上,我们使用:
$./program <input.txt >output.txt
我该如何在PowerShell中执行相同的任务?
你不能直接将文件挂钩到标准输入(stdin),但仍然可以访问stdin。
Get-Content input.txt | ./program > output.txt
input.txt
文件读入内存。如果 input.txt
的大小可能很大,请小心。 - Jack O'ConnorGet-Content
的别名,因此它们是完全相同的东西。 - JasonMArcherGet-Content
命令逐行读取内容并将其一个接一个地发送到管道中。 - mklement0如果有人像我一样在寻找大文件的“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"
cmd
命令让我能够重定向文件内容,而不会像PowerShell一样在管道中添加新行。 - undefined你可以使用输出重定向来进行:
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
或者您可以这样:
$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"
if ($exitCode){
$errItem = Get-Item "path to error file"
if ($errItem.length -gt 0){
$errors = Get-Content "path to error file" | Out-String
}
}
你也可以使用以下方法将标准错误和标准输出发送到同一位置(请注意,在cmd中,2>&1必须是最后的):
get-childitem foo 2>&1 >log
请注意,“>”与“| out-file”相同,默认编码为unicode或utf 16。同时要小心使用“>>”,因为它可能会在同一文本文件中混合ascii和unicode。"| add-content"可能比">>"更好用。"| set-content"可能比">"更可取。
我认为你只能将其保存到文本文件中,然后再读入变量。