考虑这种情况。我有多个域,并且正在编写一个涵盖所有域的脚本,以将用户添加到组中。我想做这样的事情:
# UserID selected earlier in the script
$SelectedUID = "testuser"
# These could contain any number of groups, or none at all
$CommonGroupsDomain1 = "Group1", "Group2"
$CommonGroupsDomain2 = "GroupX", "GroupY"
$CommonGroupsDomain3 = $null
# The current domain (selected earlier in the script)
$CurrentDomain = "Domain1"
If (($"CommonGroups$CurrentDomain")) {
($"CommonGroups$CurrentDomain") | ForEach-Object {
Add-ADGroupMember -Identity $_ -Members $SelectedUser -Server $CurrentDomainController
}
}
Else {
"No common groups for this domain"
}
因此,对于$CommonGroups$CurrentDomain
,是否可以告诉PS将该字符串添加作为对象名称?
这是另一种处理方式,但似乎有些笨拙:
$CommonGroups = $null
Switch ($CurrentDomain) {
'Domain1' {
$CommonGroups = $CommonGroupsDomain1
}
'Domain2' {
$CommonGroups = $CommonGroupsDomain2
}
'Domain3' {
$CommonGroups = $CommonGroupsDomain3
}
}
If ($CommonGroups) {
Add-ADGroupMember -Identity $_ -Members $SelectedUser -Server $CurrentDomainController
}
}
答案 0 :(得分:1)
此代码允许您执行所需的操作。下面的第三行将在您的if
声明中。
$CommonGroupsDomain1 = "Group1", "Group2"
$CurrentDomain = "Domain1"
Get-Variable -Name "CommonGroups$CurrentDomain" -ValueOnly