[英]Windows PowerShell - Array to function
I have this problem which makes me crazy: 我有这个让我发疯的问题:
i have a function like 我有一个像这样的功能
function xyz
{
foreach($x in $input)
{
}
}
1..10 | xyz
this is saved in a file test.ps1. 这保存在test.ps1文件中。 When I execute it like ".\\test.ps1" every time it writes that 当我每次写入时都像“。\\ test.ps1”那样执行它
cmdlet Write-Output at command pipeline position 1
Supply values for the following parameters:
InputObject[0]:
Why it is so? 为什么会这样? It does not work if I do like 如果我愿意,它不起作用
$myArray = @("a","b","c")
xyz -arr $myArray
and doing a function like 并做一个像
function xyz
{
param(
[string[]]$arr
)
foreach($x in $arr)
{
}
}
Why? 为什么?
I can't duplicate the error you're seeing but in general, when you want to process pipeline input the easiest way is like this: 我无法复制您看到的错误,但一般来说,当您想要处理管道输入时,最简单的方法是这样的:
function xyz
{
process {
$_
}
}
1..10 | xyz
The process
block will get called for every object in the pipeline. 将为管道中的每个对象调用process
块。 In fact, this is a common enough pattern that PowerShell has an even more convenient shortcut called a filter
eg: 事实上,这是一个常见的模式,PowerShell有一个更方便的快捷方式称为filter
例如:
filter xyz
{
$_
}
1..10 | xyz
Now if you need to handle regular parameters as well as pipeline input, then you need to add a param declaration and used advanced function parameter functionality eg: 现在,如果您需要处理常规参数以及管道输入,那么您需要添加一个参数声明并使用高级函数参数功能,例如:
function xyz
{
param(
[Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)]
[object[]]
$myparam
)
process {
foreach ($elem in $myparam)
{
$elem
}
}
}
xyz (1..10)
'a','b','c' | xyz
This works for both pipeline input and simple parameter (non-pipeline) usage. 这适用于管道输入和简单参数(非管道)使用。 This most closely emulates how binary cmdlets actually work. 这最接近地模拟二进制cmdlet实际工作的方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.