powershell - 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
解决方案
给参数$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'
推荐阅读
- sql - 数据库中的重复 ID
- java - 内容更改后如何重新读取文本文件的新内容?
- r - 如何在 R 中使用 `ggdraw` 和 `plot_grid()` 在一系列绘图中创建 X 和 Y 轴的公共标题?
- java - 带有地图的数据可视化
- xaml - Xamarin:NameScope 中已存在键为“X”的元素
- javascript - 轮播中的模态
- c - 我想将 c 模式打印为上三角形
- r - ConfirmSweetAlert 在闪亮中生成的确认按钮的功能
- python-3.x - 如何让我的 discord py bot dm 某人
- laravel - 作曲家需要 laravel/ui。不要安装照明/控制台 v7.12.0