我有一个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".为什么$headers被读取为字符串而不是NameValueCollection?
发布于 2014-02-25 02:38:17
数组和集合在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。
https://stackoverflow.com/questions/22002743
复制相似问题