我正在尝试编写一个PowerShell脚本,它可以获取管道输入(预计会这样做),但尝试如下内容
ForEach-Object {
# do something
}
在命令行中使用脚本时实际上不起作用,如下所示:
1..20 | .\test.ps1
有什么办法吗?
注意:我了解函数和过滤器。这不是我要找的。
发布于 2009-05-20 11:34:06
在v2中,您还可以接受管道输入(通过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
发布于 2009-05-20 00:03:48
您可以编写一个过滤器,它是函数的一个特例,如下所示:
filter SquareIt([int]$num) { $_ * $_ }
或者您可以创建一个类似的函数,如下所示:
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
}
}
上面的代码是作为一个交互函数定义的,或者如果在一个脚本中可以加入到你的全局会话(或其他脚本)中。但是,您的示例表明您需要一个脚本,所以这里的脚本可以直接使用(不需要打点):
--- 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中,这一点有所改变,因为“高级函数”赋予函数与已编译的cmdlet相同的参数绑定功能。有关不同之处的示例,请参阅此blog post。还要注意,在这种高级函数情况下,不使用$_来访问管道对象。使用高级函数时,管道对象将绑定到参数,就像绑定cmdlet一样。
发布于 2012-08-09 17:05:56
下面是使用管道输入的脚本/函数的最简单示例。每一个都与通过管道连接到"echo“cmdlet的行为相同。
作为脚本:
Echo-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
}
As函数:
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
https://stackoverflow.com/questions/885349
复制相似问题