【问题标题】:Powershell - can I use a string as an object in a conditional? [duplicate]Powershell - 我可以在条件中使用字符串作为对象吗? [复制]
【发布时间】:2020-04-28 10:40:21
【问题描述】:

考虑这种情况。我有多个域,并且正在编写一个涵盖所有域的脚本以将用户添加到组中。我想做这样的事情:

# 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
     }
}

【问题讨论】:

  • 在您的示例中,$CommonGroups$CurrentDomain 的一种可能评估是什么?
  • 在上面的例子中,值是 $CommonGroupsDomain1,所以表达式实际上是 If ($CommonGroupsDomain1) { .....
  • 在上面添加了说明。

标签: powershell


【解决方案1】:

此代码允许您做您想做的事。下面的第三行将在您的 if 声明中。

$CommonGroupsDomain1 = "Group1", "Group2"

$CurrentDomain = "Domain1"

Get-Variable -Name "CommonGroups$CurrentDomain" -ValueOnly 

【讨论】:

    猜你喜欢
    • 2018-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多