David Klempfner
David Klempfner

Reputation: 9870

Powershell Function Has Unexpected Return Value

I have this Powershell code:

function getEmailHeaders
{
    [System.Collections.Specialized.NameValueCollection]$headers = New-Object System.Collections.Specialized.NameValueCollection
    $headers.Add("name1", "VER=2011.2, NS=test.au, SEC=UNCLASSIFIED, [email protected]")
    return $headers
}

Then in my main method I have:

[System.Collections.Specialized.NameValueCollection]$headers = getEmailHeaders

However this throws the following exception:

System.Management.Automation.ArgumentTransformationMetadataException: Cannot convert the "name1" value of type "System.String" to type "System.Collections.Specialized.NameValueCollection". ---> System.Management.Automation.PSInvalidCastException
: Cannot convert the "name1" value of type "System.String" to type "System.Collections.Specialized.NameValueCollection".

Why is $headers being read as a String rather than a NameValueCollection?

Upvotes: 1

Views: 1267

Answers (1)

Keith Hill
Keith Hill

Reputation: 201652

Arrays and collections are treated specially in PowerShell. Returning a collection is resulting in the collection being enumerated as the output of the function. Try it this way:

function getEmailHeaders
{
    [System.Collections.Specialized.NameValueCollection]$headers = New-Object System.Collections.Specialized.NameValueCollection
    $headers.Add("name1", "VER=2011.2, NS=test.au, SEC=UNCLASSIFIED, [email protected]")
    ,$headers
}

This will wrap the collection in an extra array just so that when the array is enumerated it returns its one and only element - a NameValueCollection.

Upvotes: 3

Related Questions