如何编写一个接受pipe道input的PowerShell脚本?
我想写一个PowerShell脚本,可以得到pipe道input(并希望这样做),但尝试类似的东西
ForEach-Object { # do something } 
从命令行使用脚本时,实际上不起作用,如下所示:
 1..20 | .\test.ps1 
有没有办法?
注:我知道function和filter。 这不是我正在寻找的。
这工作,并可能有其他方法来做到这一点:
 foreach ($i in $input) { $i } 
  17:12:42 PS> 1..20 |  \ CMD-input.ps1 
  1 
  2 
  3 
  – 剪断 –  
  18 
  19 
  20 
 search“powershell $inputvariables”,你会发现更多的信息和例子。 
 一对夫妇在这里: 
  PowerShellfunction和filterPowerShell Pro! 
  (请参阅“使用PowerShell特殊variables”$ input“”一节) 
  “脚本,函数和脚本块都可以访问$ inputvariables,这个variables提供了一个枚举器来覆盖传入pipe道中的元素。” 
 要么 
  $ input gotchas«德米特里的PowerBlog PowerShell及更高版本 
  “…基本上$input在一个提供访问你的pipe道的枚举器。” 
 对于PS命令行,不是DOS命令行 Windows命令处理器。 
在v2中,您还可以接受pipe道input(通过propertyName或byValue),添加参数别名等:
 function Get-File{ param( [Parameter( Position=0, Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true) ] [Alias('FullName')] [String[]]$FilePath ) process { foreach($path in $FilePath) { Write-Host "file path is: $path" } } } # test ValueFromPipelineByPropertyName dir | Get-File # test ValueFromPipeline (byValue) "D:\scripts\s1.txt","D:\scripts\s2.txt" | Get-File - or - dir *.txt | foreach {$_.fullname} | Get-File 
你可以写一个filter,这是一个function的特例,如下所示:
 filter SquareIt([int]$num) { $_ * $_ } 
或者你可以像这样创build一个类似的function:
 function SquareIt([int]$num) { Begin { # Executes once before first item in pipeline is processed } Process { # Executes once for each pipeline object $_ * $_ } End { # Executes once after last pipeline object is processed } } 
上面的工作作为一个交互function定义,或者如果在一个脚本可以被点到你的全局会话(或另一个脚本)。 然而,你的例子表明你想要一个脚本,所以这里是一个脚本,可以直接使用(不需要点):
  --- Contents of test.ps1 --- param([int]$num) Begin { # Executes once before first item in pipeline is processed } Process { # Executes once for each pipeline object $_ * $_ } End { # Executes once after last pipeline object is processed } 
使用PowerShell V2,这个变化有点“高级function”,这些function使用与编译的cmdlet具有相同参数绑定function的function。 看到这个博客文章的差异的一个例子。 另外请注意,在这个高级function的情况下,您不要使用$ _来访问pipe道对象。 使用高级函数,pipe道对象会像使用cmdlet一样绑定到参数。
以下是使用pipe道input的脚本/函数的最简单示例。 每个行为与“echo”cmdletpipe道相同。
作为脚本:
#回声pipe.ps1
  Begin { # Executes once before first item in pipeline is processed } Process { # Executes once for each pipeline object echo $_ } End { # Executes once after last pipeline object is processed } 
#Echo-Pipe2.ps1
 foreach ($i in $input) { $i } 
作为功能:
 Function Echo-Pipe { Begin { # Executes once before first item in pipeline is processed } Process { # Executes once for each pipeline object echo $_ } End { # Executes once after last pipeline object is processed } } Function Echo-Pipe2 { foreach ($i in $input) { $i } } 
例如
 PS > . theFileThatContainsTheFunctions.ps1 # This includes the functions into your session PS > echo "hello world" | Echo-Pipe hello world PS > cat aFileWithThreeTestLines.txt | Echo-Pipe2 The first test line The second test line The third test line