Han*_*ood 7 powershell pipeline function
我发现通过PowerShell管道将string对象传递给函数会将它们转换为对象.如果我将对象作为参数传递,它会保留其类型.展示:
我有以下PowerShell函数,它显示对象的类型和值:
function TestFunction {
param (
[Parameter(
Position=0,
Mandatory=$true,
ValueFromPipeline=$true
)] $InputObject
)
Echo $InputObject.GetType().Name
Echo $InputObject
}
Run Code Online (Sandbox Code Playgroud)
我运行此脚本来测试函数:
[string[]] $Array = "Value 1", "Value 2"
# Result outside of function.
Echo $Array.GetType().Name
Echo $Array
Echo ""
# Calling function with parameter.
TestFunction $Array
Echo ""
# Calling function with pipeline.
$Array | TestFunction
Run Code Online (Sandbox Code Playgroud)
这会产生输出:
String[]
Value 1
Value 2
String[]
Value 1
Value 2
String
Value 2
Run Code Online (Sandbox Code Playgroud)
编辑:我如何使用管道将整个数组传递给函数?
要处理通过管道收到的多个项目,您需要在函数中使用一个过程块:
function Test-Function {
param (
[Parameter(ValueFromPipeline=$true)] $Test
)
process {
$Test.GetType().FullName
$Test
}
}
[string[]] $Array = "Value 1", "Value 2"
$Array | Test-Function
Run Code Online (Sandbox Code Playgroud)
更多信息:
get-help about_functions http://technet.microsoft.com/en-us/library/dd347712.aspxget-help about_Functions_Advanced http://technet.microsoft.com/en-us/library/dd315326.aspx| 归档时间: |
|
| 查看次数: |
2064 次 |
| 最近记录: |