powershell - 使 arraylist 上的 select -unique 返回 arraylist 而不是字符串

标签 powershell

我在下面的类中有三个数组列表。我想让它们保持独特。但是,如果数组列表中只有一项(字符串)并且您使用 select -unique (或任何其他方法来实现此目的),它将返回字符串而不是字符串列表。用 @() 包围它也不起作用,因为这会将其转换为数组而不是数组列表,而我无法向其中添加内容。

有什么仍然有效的建议吗?我之前尝试过 HashSets,但不知何故有一些可怕的经历。请参阅我之前的帖子.. Post on hashset issue

代码如下:

Class OrgUnit
{
    [String]$name
    $parents
    $children
    $members


    OrgUnit($name){
        $this.name = $name
        $this.parents = New-Object System.Collections.ArrayList
        $this.children = New-Object System.Collections.ArrayList
        $this.members = New-Object System.Collections.ArrayList
    }

    addChild($child){
        # > $null to supress output
        $tmp = $this.children.Add($child)
        $this.children = $this.children | select -Unique
    }

    addParent($parent){
        # > $null to supress output
        $tmp = $this.parents.Add($parent) 
        $this.parents = $this.parents | select -Unique
    }

    addMember($member){
        # > $null to supress output
        $tmp = $this.members.Add($member)
        $this.members = $this.members | select -Unique
    }
}

最佳答案

您要向数组中添加一个新项目,然后从中选择唯一的项目,并在每次添加成员时重新评估它。这是非常低效的,也许可以尝试以下方法:

if (-not $this.parents.Contains($parent)) {
  $this.parents.Add($parent) | out-null
}

即使使用 out-null 抑制效率最低的输出,也会快得多。

关于powershell - 使 arraylist 上的 select -unique 返回 arraylist 而不是字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58932348/

相关文章:

powershell - 对列数未知的 CSV 进行分组和求和

regex - 仅使用起始值匹配多行事件

在 powershell 中将 XML 转换为 CSV (Spacewalk)

azure - Powershell 错误Remove-AzureStorageBlob 未找到方法 : 'Void

powershell - Powershell在远程计算机上安装/卸载Windows服务

powershell - PowerShell 的 Get-ChildItem cmdlet 返回的可能的 'Mode' 值是什么?

Powershell 远程处理和页面文件

windows - 运行独立的 Windows Powershell

windows - 从 Powershell 更新计划任务脚本

powershell - 使用 AzureRM powershell 创建和发布 Azure 经典云服务项目