Question:
I’m finding that passing objects to functions through the PowerShell pipeline converts them to string
objects. If I pass the object as a parameter it keeps its type. To demonstrate:
I have the following PowerShell function which displays a object’s type and value:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
function TestFunction { param ( [Parameter( Position=0, Mandatory=$true, ValueFromPipeline=$true )] $InputObject ) Echo $InputObject.GetType().Name Echo $InputObject } |
I ran this script to test the function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
[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 |
This produces the output:
1 2 3 4 5 6 7 8 9 10 11 |
String[] Value 1 Value 2 String[] Value 1 Value 2 String Value 2 |
EDIT: How can I use the pipeline to pass an entire array to a function?
Answer:
To process multiple items recieved via the pipeline you need a process block in your function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
function Test-Function { param ( [Parameter(ValueFromPipeline=$true)] $Test ) process { $Test.GetType().FullName $Test } } [string[]] $Array = "Value 1", "Value 2" $Array | Test-Function |
More info:
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