1

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?

3
  • 1
    Why isn't $headers a hashtable? Commented Feb 25, 2014 at 2:29
  • because I need to use a NameValueCollection, not a Hashtable. Commented Feb 25, 2014 at 2:48
  • I'm trying to add to the MailMessage.Headers property: msdn.microsoft.com/en-us/library/… Commented Feb 25, 2014 at 2:51

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This seems really annoying/unintuitive, is there a reason for Powershell working this way? Maybe my way of thinking is biased since I come from a C# background?
Remember that PowerShell is a "shell" scripting language. Shell scripting languages typically treat functions as a named set of individual command lines where each command line contributes to the output of the overall function. And in general PowerShell is heavily oriented towards unrolling collections down the pipeline - kind of like LINQ processes IEnumerable<T>. Typically that is what you want in a PowerShell pipeline - operate on each object in the collection. Occasionally that behavior gets in the way. :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.