将标准输入(读取主机)重定向到 Powershell 脚本 [英] Redirect standard input (read-host) to a Powershell script

查看:28
本文介绍了将标准输入(读取主机)重定向到 Powershell 脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个示例 powershell 脚本:

Here's a sample powershell script:

$in = read-host -prompt "input"
write-host $in

这是一个示例test.txt"文件:

Here's a sample 'test.txt' file:

hello

并且我们希望将管道输入从powershell传递给它.这是我尝试过的一些:

And we want to pass piped input to it from powershell. Here's some I have tried:

.\test.ps1 < test.txt
.\test.ps1 < .\test.txt
.\test.ps1 | test.txt
.\test.ps1 | .\test.txt
test.txt | .\test.ps1
.\test.txt | .\test.ps1
get-content .\test.txt | .\test.ps1

即使只是尝试回显输入也不起作用:

even just trying to echo input doesn't work either:

echo hi | \.test.ps1

上面没有产生错误的每个示例总是提示用户而不是接受管道输入.

Every example above that doesn't produce an error always prompts the user instead of accepting the piped input.

注意:我的 powershell 版本表显示为 4.0.-1.-1

Note: My powershell version table says 4.0.-1.-1

谢谢

编辑/结果:对于那些正在寻找解决方案的人,您不能通过管道将输入传输到 powershell 脚本.你必须更新你的PS文件.请参阅下面的片段.

Edit/Result: To those looking for a solution, you cannot pipe input to a powershell script. You have to update your PS file. See the snippets below.

推荐答案

问题在于您的脚本 \.test.ps1 不期望该值.

The issue is that your script \.test.ps1 is not expecting the value.

试试这个:

param(
    [parameter(ValueFromPipeline)]$string
)

# Edit: added if statement
if($string){
    $in = "$string"
}else{
    $in = read-host -prompt "input"
}

Write-Host $in

或者,您可以使用没有 param 部分的魔法变量 $input(我不完全理解这一点,所以不能真正推荐它):

Alternatively, you can use the magic variable $input without a param part (I don't fully understand this so can't really recommend it):

Write-Host $input

这篇关于将标准输入(读取主机)重定向到 Powershell 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆