PowerShell 创建哈希表(如果不存在)并添加值



目前我正在手动创建一个哈希表,以便我可以迭代

$aceList = @{
    "Domainjdoe" = "Change, Submit, GetPassword"
    "Domainssmith" = "Change, Submit, GetPassword"
    "Domainmsmith" = "Submit"
}

但是,这不允许我更多地抽象它。

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

function Set-HashTable {
    Param(
        [String]$Identity,
        [String]$Access,
        [Hashtable]$ACL
    )
    $ACL.Add($Identity, $Access)
    return $ACL
}
$acl = @{}
$acl = Set-ACL -Identity "Domainjdoe" -Access "Change, Submit, GetPassword" -ACL $acl
$acl = Set-ACL -Identity "Domainssmith" -Access "Change, Submit, GetPassword" -ACL $acl
$acl = Set-ACL -Identity "Domainmsmith" -Access "Submit" -ACL $acl

为参数$ACL指定默认值,您可以避免传递初始空哈希表:

function Set-HashTable {
    Param(
        [String]$Identity,
        [String]$Access,
        [Hashtable]$ACL = @{}
    )
    $ACL.Add($Identity, $Access)
    return $ACL
}
$acl = Set-HashTable -Identity 'Domainjdoe' -Access 'Change, Submit, GetPassword'
$acl = Set-HashTable -Identity 'Domainssmith' -Access 'Change, Submit, GetPassword' -ACL $acl
$acl = Set-HashTable -Identity 'Domainmsmith' -Access 'Submit' -ACL $acl

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

$acl = @{}
$acl.Add('Domainjdoe', 'Change, Submit, GetPassword')
$acl.Add('Domainssmith', 'Change, Submit, GetPassword')
$acl.Add('Domainmsmith', 'Submit')

或者像这样:

$acl = @{}
$acl['Domainjdoe']   = 'Change, Submit, GetPassword'
$acl['Domainssmith'] = 'Change, Submit, GetPassword'
$acl['Domainmsmith'] = 'Submit'

最新更新