微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

PowerShell返回对象时添加项目的int索引

如何解决PowerShell返回对象时添加项目的int索引

在这里看到了很多类似的问题,但是没有一个解决方案对我有用。

我有一个看起来像这样的函数

const element = document.querySelector('#myParagraph');
element.innerHTML = 'Hello World';

被这样称呼的

function Get-ManagedDevices {

    # ...(params and stuff here)...

    $batchResponse = Invoke-RestMethod @restParams
    $responses = @{}
    foreach ($response in $batchResponse.responses) {
        $responses.Add($response.id,$response.body) > $null
    }
    return,$responses
}

当我在函数调用中进行调试时,当我看到$ response变量时,得到的是期望值

$data = Get-Devices -Accesstoken $Accesstoken -deviceids $deviceids

但是,当我尝试在函数调用后使用PS> $responses Name Value ---- ----- d1290207-c693-4663-88bf-58512… @{@odata.context=https://graph.microsoft.com/v1.0/$Metadat… 7ad71b70-b992-490f-8822-1561a… @{@odata.context=https://graph.microsoft.com/v1.0/$Metadat… PS> $responses.count 1 变量时,我得到了

$data

我很困惑。我用PS> $data 0 1 Name Value ---- ----- d1290207-c693-4663-88bf-58512… @{@odata.context=https://graph.microsoft.com/v1.0/$Metadat… 7ad71b70-b992-490f-8822-1561a… @{@odata.context=https://graph.microsoft.com/v1.0/$Metadat… PS> $data.count 3 用管道将变量添加到哈希表的$ null中。 我添加了带有>$null之类的返回值的一元运算符,这是'about_return'PowerShell文档中的建议。 我尝试省略return关键字,而是使用ArrayList,而是使用数组,等等...

到底发生了什么,为什么我不能从该函数返回哈希表?我觉得我快疯了。

解决方法

about_Return文档没有提到直接从函数返回哈希表。您提到的常见问题是返回整个数组的能力,而不是沿管道迭代的能力。

返回哈希表很常见。乍一看,您的代码可能是:

function Get-ManagedDevices {

    # ...(params and stuff here)...

    $batchResponse = Invoke-RestMethod @restParams
    $responses = @{}
    foreach ($response in $batchResponse.responses) {
        $responses.Add($response.id,$response.body)
    }
    return $responses
}

那应该没有那么复杂。删除逗号,返回哈希时无效。 >$null对哈希表.Add(...)方法没有影响。

给出您的结果和示例,您以前使用ArrayList进行尝试时可能会出现一些伪像。 ArrayList上的.Add(...)方法将发出要添加到的索引号。当我们忘记使用[void]| Out-Null$null = ...Add(...)时,通常会导致有害的输出污染管道。当您获得2个索引号时,您的数据就...

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。