我有这个Powershell代码:
function getEmailHeaders
{
[System.Collections.Specialized.NameValueCollection]$headers = New-Object System.Collections.Specialized.NameValueCollection
$headers.Add("name1", "VER=2011.2, NS=test.au, SEC=UNCLASSIFIED, ORIGIN=no-reply@test.bv.au")
return $headers
}
然后在我的主要方法中我有:
[System.Collections.Specialized.NameValueCollection]$headers = getEmailHeaders
然而,这会引发以下异常:
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".
为什么$ header被读取为String而不是NameValueCollection?
答案 0 :(得分:3)
在PowerShell中专门处理数组和集合。返回集合会导致集合被枚举为函数的输出。试试这种方式:
function getEmailHeaders
{
[System.Collections.Specialized.NameValueCollection]$headers = New-Object System.Collections.Specialized.NameValueCollection
$headers.Add("name1", "VER=2011.2, NS=test.au, SEC=UNCLASSIFIED, ORIGIN=no-reply@test.bv.au")
,$headers
}
这会将集合包装在一个额外的数组中,以便在枚举数组时返回其唯一的元素 - NameValueCollection。