重定向标准输入(读取主机)为PowerShell脚本



这是一个示例powershell脚本:

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

这是示例'test.txt'文件:

hello

我们想从powershell传递管道输入。这是我尝试的:

.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

即使只是试图回声输入也不起作用:

echo hi | .test.ps1

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

注意:我的PowerShell版本表4.0.-1

谢谢

编辑/结果:对于那些寻求解决方案的人,您无法将输入输入到PowerShell脚本上。您必须更新PS文件。请参阅下面的摘要。

您无法将输入输入到Read-Host,但不需要这样做。

PowerShell不支持输入重定向(<(。实际上,这不是(重要的(限制,因为可以将a < b重写为b | a(即,将b的输出作为输入发送到a(。

powershell可以提示输入参数,如果参数的值丢失并且将其设置为强制性属性。例如:

function test {
  param(
    [parameter(Mandatory=$true)] [String] $TheValue
  )
  "You entered: $TheValue"
}

如果您不提供$TheValue参数的输入,PowerShell将提示。

此外,您可以指定参数接受管道输入。示例:

function test {
  param(
    [parameter(ValueFromPipeline=$true)] [String] $TheValue
  )
  process {
    foreach ( $item in $TheValue ) {
      "Input: $item"
    }
  }
}

所以如果您写

"A","B","C" | test

该功能将输出以下内容:

Input: A
Input: B
Input: C

所有这些都是在PowerShell文档中简洁明了的。

问题是您的脚本.test.ps1不期望该值。

尝试以下操作:

param(
    [parameter(ValueFromPipeline)]$string
)
# Edit: added if statement
if($string){
    $in = "$string"
}else{
    $in = read-host -prompt "input"
}
Write-Host $in

另外,您可以在没有param零件的情况下使用魔术变量$input(我不完全理解这一点,所以无法真正推荐它(:

Write-Host $input

是;在Powershell 5.1中" lt;&quot"未实施(糟糕(

所以,这行不通:tenkeyf&lt;C: Users Marcus Work data.num

但是,

this Will:类型C: Users Marcus Work data.num |tenkeyf

...

powerShell没有重定向机制,但是.net具有。

您可以使用[System.diagnostics.process]实现重定向输入的目的。

相关的Microsoft文档如下。

过程类

这是一个示例程序,可在我的Windows 10 Computer上完美奏效

function RunAndInput{
    $pi = [System.Diagnostics.ProcessStartInfo]::new()
    $pi.FileName ="powershell"
    $pi.Arguments = """$PSScriptRootreceiver.ps1"""
    $pi.UseShellExecute = $false
    $pi.RedirectStandardInput = $true
    $pi.RedirectStandardOutput = $true
    $p = [System.Diagnostics.Process]::Start($pi)
    $p.StandardInput.WriteLine("abc"+ "`r`n");
    $p.StandardOutput.ReadToEnd()
    $p.Kill()
}
RunAndInput

# OutPut
Please enter the information: abc
Received:abc
# receiver.ps1
('Received:' + (Read-Host -Prompt 'Please enter the information'))

希望帮助您!

最新更新