为什么在PowerShell中标准输入未从控制台键盘重定向到文本文件?

huangapple go评论70阅读模式
英文:

Why standard input is not redirected from console keyboard to text file in PowerShell

问题

我有一个简单的PowerShell脚本:

$stdin = [System.IO.StreamReader]::new([System.Console]::OpenStandardInput())

while (!$stdin.EndOfStream) {
    $line = $stdin.ReadLine()
    $output = "Processed: $line"
    [System.Console]::Out.WriteLine($output)
}

如果我启动PowerShell控制台并插入以下命令:
type myfile.txt | ./myscript.ps1
脚本不会按照我的期望读取文件的行,而是读取标准键盘控制台输入。为什么会这样?我如何通过管道在脚本中读取文本行?

谢谢您的任何想法。

英文:

I have a simple powershell script:

$stdin = [System.IO.StreamReader]::new([System.Console]::OpenStandardInput())

while (!$stdin.EndOfStream) {
    $line = $stdin.ReadLine()
    $output = "Processed: $line"
    [System.Console]::Out.WriteLine($output)
}

if I start the powershell console and insert following command:
type myfile.txt | ./myscript.ps1 the script doesn't read the lines of the file as I expect, rather it reads the standard keyboard console input. Why is it so? How could I read text lines in script through the pipeline?

Thank you for any ideas.

答案1

得分: 1

在PowerShell中,宿主应用程序(在大多数情况下是powershell.exepwsh.exe)负责执行的脚本的I/O。

如果你想在你的脚本中接收任意管道输入,可以使用自动变量$Input

# myscript.ps1

$Input | ForEach-Object {
  $line = $_
  Write-Host "Processed: '$line'"
}

现在你可以执行:

type myfile.txt | ./myscript.ps1
英文:

In PowerShell, the host application (in most cases powershell.exe or pwsh.exe) takes care of I/O for the scripts you execute.

If you want to take arbitrary pipeline input in your scripts, use the automatic $Input enumerator variable:

# myscript.ps1

$Input |ForEach-Object {
  $line = $_
  Write-Host "Processed: '$line'"
}

Now you can do:

type myfile.txt | ./myscript.ps1

huangapple
  • 本文由 发表于 2023年7月17日 20:11:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76704342.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定