首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Powershell函数具有意外的返回值。

问Powershell函数具有意外的返回值。
EN

Stack Overflow用户
提问于 2014-02-25 01:20:56
回答 1查看 1.1K关注 0票数 1

我有一个Powershell代码:

代码语言:javascript
复制
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
}

然后在我的主要方法中:

代码语言:javascript
复制
[System.Collections.Specialized.NameValueCollection]$headers = getEmailHeaders

但是,这会引发以下异常:

代码语言:javascript
复制
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?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-02-25 02:38:17

数组和集合在PowerShell中是专门处理的。返回集合将导致将集合枚举为函数的输出。这样试一试:

代码语言:javascript
复制
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。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22002743

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档