首页 > 解决方案 > PowerShell 如果不存在则创建哈希表并添加值

问题描述

目前我正在使用手动创建的哈希表,以便可以迭代

$aceList = @{
    "Domain\jdoe" = "Change, Submit, GetPassword"
    "Domain\ssmith" = "Change, Submit, GetPassword"
    "Domain\msmith" = "Submit"
}

但是,这不允许我对其进行更多抽象。

理想情况下,我想要的是这样的东西,而不必设置$acl = @{}函数的外部?

function Set-HashTable {
    Param(
        [String]$Identity,
        [String]$Access,
        [Hashtable]$ACL
    )
    $ACL.Add($Identity, $Access)
    return $ACL
}

$acl = @{}
$acl = Set-ACL -Identity "Domain\jdoe" -Access "Change, Submit, GetPassword" -ACL $acl
$acl = Set-ACL -Identity "Domain\ssmith" -Access "Change, Submit, GetPassword" -ACL $acl
$acl = Set-ACL -Identity "Domain\msmith" -Access "Submit" -ACL $acl

标签: powershell

解决方案


给参数$ACL一个默认值,你可以避免传递初始的空哈希表:

function Set-HashTable {
    Param(
        [String]$Identity,
        [String]$Access,
        [Hashtable]$ACL = @{}
    )
    $ACL.Add($Identity, $Access)
    return $ACL
}

$acl = Set-HashTable -Identity 'Domain\jdoe' -Access 'Change, Submit, GetPassword'
$acl = Set-HashTable -Identity 'Domain\ssmith' -Access 'Change, Submit, GetPassword' -ACL $acl
$acl = Set-HashTable -Identity 'Domain\msmith' -Access 'Submit' -ACL $acl

话虽如此,我看不到封装操作的优势,例如将键/值对添加到函数中的哈希表。直接这样做要简单得多,如下所示:

$acl = @{}
$acl.Add('Domain\jdoe', 'Change, Submit, GetPassword')
$acl.Add('Domain\ssmith', 'Change, Submit, GetPassword')
$acl.Add('Domain\msmith', 'Submit')

或像这样:

$acl = @{}
$acl['Domain\jdoe']   = 'Change, Submit, GetPassword'
$acl['Domain\ssmith'] = 'Change, Submit, GetPassword'
$acl['Domain\msmith'] = 'Submit'

推荐阅读