首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >创建通过Powershell循环的函数

创建通过Powershell循环的函数
EN

Stack Overflow用户
提问于 2020-05-05 10:26:26
回答 1查看 127关注 0票数 1

我正在尝试创建一个函数来循环json文件,并根据特定条件满足,希望将json键的值添加到数组中,但无法完成相同的任务。

以下是联合选举委员会:

代码语言:javascript
复制
$a1 = [    {
        "name": "sachin",
        "surname": "",
    },
    {
        "name": "Rajesh",
        "surname": "Mehta"

    }
]

我创建的函数如下:

代码语言:javascript
复制
function addingkeyval
{
param ($key,
        [Array]$tobeaddedarr)

$a1 | Select-Object -Property name,surname | ForEach-Object {
    if($_.$key-eq "")
    {
    }
    else
    {     
    $tobeaddedarr +=$_.$key+","
    }
}

}

当我在这个函数中使用以下语句时:

代码语言:javascript
复制
$surnamearr = @()
addingkeyval -key surname -tobeaddedarr $surnamearr

i want the output in the array $surnamearr as below
("Mehta")

不知何故,我无法在数组中增加价值,有人能帮助我实现同样的目标吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-05 11:33:28

代码语言:javascript
复制
$surnamearr = ([string[]] (ConvertFrom-Json $a1).surname) -ne ''

  • ConvertFrom-Json $a1将JSON数组转换为PowerShell自定义对象数组(键入[pscustomobject]).

)

提取结果数组中对象的所有.surname属性的值。

  • Cast [string[]]确保将结果作为数组处理(如果$a1中的数组碰巧只包含一个元素,则不会处理),并显式地将其转换为字符串,因此通过-ne ''过滤非空值也适用于不具有.surname属性的输入对象。

  • -ne ''过滤掉结果数组中的所有空字符串元素(使用数组作为LHS,比较运算符(如-ne )充当数组筛选器,而不是返回布尔值)。

结果是,$surnamearr是一个包含所有非空.surname属性值的数组。

至于,你尝试过

$tobeaddedarr +=$_.$key+","

该语句隐式地创建一个新数组,与调用者通过$tobeaddedarr参数变量传递的数组引用不同-因此,调用方从未看到更改。

通常不能传递要附加到就地的数组,因为数组相对于元素的数量是不可变的。

虽然您可以传递一个类似数组的可变结构(比如[System.Collections.Generic.List[object]]实例,您可以用它的.Add()方法附加到它),但是在函数中构建一个新数组并输出它要简单得多。

因此,您可以将您的函数编写为:

代码语言:javascript
复制
function get-keyval
{
  param ($key)

  # Implicitly output the elements of the array output by using this command.
  ([string[]] (ConvertFrom-Json $key).surname) -ne ''
}

$surnamearr = get-keyval surname

注意:

默认情况下,

  • 在PowerShell中输出数组或集合将枚举它:它一个一个地将其元素发送到输出流(管道)。

代码语言:javascript
复制
- While it is possible to output an array _as a whole_, via the unary form of `,`, the array-construction operator ( `, (([string[]] (ConvertFrom-Json $a1).surname) -ne '')`), which improves performance, the problem is that the caller may not expect this behavior, especially not in a _pipeline_.

如果您在一个变量(如此处的

  • )中捕获输出,PowerShell将自动为您收集[object[]]数组中的单个输出对象;但是,请注意,单个输出对象按原样返回,即不包装在数组中。

代码语言:javascript
复制
- You can wrap `@(...)` around the function call to ensure that you _always_ get an array
- Alternatively, type-constrain the receiving variable: `[array] $surnamearr = ...`, which also creates an `[object[]]` array, or something like `[string[]] $surnamearr = ...`, which creates a strongly typed string array.
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61610940

复制
相关文章

相似问题

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