Nit*_*tin 39 powershell stdin powershell-2.0
在Windows PowerShell上重定向标准输入/输出所需的语法是什么?
在Unix上,我们使用:
$./program <input.txt >output.txt
Run Code Online (Sandbox Code Playgroud)
如何在PowerShell中执行相同的任务?
Jas*_*her 50
您不能将文件直接挂接到stdin,但您仍然可以访问stdin.
Get-Content input.txt | ./program > output.txt
Run Code Online (Sandbox Code Playgroud)
tsc*_*ors 17
如果有人在寻找大文件的“Get-Content”替代方案(如我),您可以在 PowerShell 中使用 CMD:
cmd.exe /c ".\program < .\input.txt"
Run Code Online (Sandbox Code Playgroud)
或者您可以使用此 PowerShell 命令:
Start-Process .\program.exe -RedirectStandardInput .\input.txt -NoNewWindow -Wait
Run Code Online (Sandbox Code Playgroud)
它将在同一窗口中同步运行程序。但是当我在 PowerShell 脚本中运行它时,我无法找到如何将此命令的结果写入变量,因为它总是将数据写入控制台。
编辑:
要从 Start-Process 获取输出,您可以使用选项
-重定向标准输出
用于将输出重定向到文件,然后从文件中读取它:
Start-Process ".\program.exe" -RedirectStandardInput ".\input.txt" -RedirectStandardOutput ".\temp.txt" -NoNewWindow -Wait
$Result = Get-Content ".\temp.txt"
Run Code Online (Sandbox Code Playgroud)
小智 8
对于输出重定向,您可以使用:
command > filename Redirect command output to a file (overwrite)
command >> filename APPEND into a file
command 2> filename Redirect Errors
Run Code Online (Sandbox Code Playgroud)
输入重定向以不同的方式工作.例如,请参阅此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"
Run Code Online (Sandbox Code Playgroud)
如果您想知道进程是否出错,请添加以下代码:
$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
}
}
Run Code Online (Sandbox Code Playgroud)
我发现,当您需要处理外部程序/进程时,这样我确实可以更好地处理脚本的执行。否则,我会遇到脚本因某些外部进程错误而挂起的情况。
| 归档时间: |
|
| 查看次数: |
30424 次 |
| 最近记录: |