英文:
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.exe
或pwsh.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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论