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

时间:2012-07-12 08:10:41

标签: powershell powershell-v2.0 stdin

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

在Unix上,我们使用:

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

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

5 个答案:

答案 0 :(得分:41)

您无法将文件直接挂接到stdin,但您仍然可以访问stdin。

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

答案 1 :(得分:7)

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

  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

答案 2 :(得分:2)

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

Invalid value(s)

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


function download(filename, text) {
  var element = document.createElement('a');
  element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
  element.setAttribute('download', filename);

  element.style.display = 'none';
  document.body.appendChild(element);

  element.click();

  document.body.removeChild(element);
}

// Start file download.
download("hello.txt","This is the content of my file :)");

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

编辑:

要从启动过程中获取输出,可以使用选项

  

-RedirectStandardOutput

用于将输出重定向到文件(由js2010建议),然后从文件中读取:

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

答案 3 :(得分:0)

您也可以执行此操作以使标准错误和标准输出转到同一位置:

get-childitem foo 2>&1> log

请注意“>”与“ | out-file”相同,默认情况下,编码为u​​nicode或utf16。也请注意“ >>”,因为它可以在同一文本中混合ascii和unicode文件。 “ |添加内容”可能比“ >>”更好。 “ | set-content”可能比“>”更好。

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

我想您所能做的就是保存到文本文件,然后再将其读入变量。

答案 4 :(得分:0)

或者您可以这样做:

类似:

- name: Find all files with extension .json under folder and all sub folders
  find:
    paths: /var/log/conf/login/
    patterns: '*.json'
    recurse: yes

- name: Replace string in files
  replace:
    dest: /var/log/conf/login/ # I have try with path instead dest but nothing cannot make is work
    regexp: 'logs'
    replace: 'LOGINS'

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

$ exitCode = $ proc.get_ExitCode()

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

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

相关问题