Powershell-我可以在条件中使用字符串作为对象吗?

怀疑论者

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

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

此代码允许您执行所需的操作。下面的第三行将在您的if陈述中。

$CommonGroupsDomain1 = "Group1", "Group2"

$CurrentDomain = "Domain1"

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

我可以在 Visual Basic 中使用字符串作为名称来更改对象属性吗?

在powershell中使用JSON对象构建字符串

我可以在python中使用字符串作为命名参数吗

我可以在C ++中使用字符串作为注释吗?

我可以在QComboBox中使用字符串作为索引吗?

我可以在PowerShell中使用“ &&”或“ -and”吗?

PowerShell:使用字符串和哈希表

在Powershell中用字符串拆分

我可以将字符串变量从Eclipse(java)发送到Powershell脚本吗

使用字符串替换在Powershell中插入字符串“ $ _”?

在If- else中使用字符串作为条件

使用扩展字符串作为Powershell函数参数

为什么我可以在HashMap中使用字符串作为键?

为什么在PowerShell中使用逗号连接字符串?

在Powershell中使用搜索字符串编辑文件

在Powershell中使用Empy字符串键解析JSON

在Powershell中使用机器密钥加密字符串?

PowerShell:在字符串中使用未声明的变量

在Powershell中使用选择字符串排除搜索模式

我可以在document.getElementById()中使用字符串变量吗?

我们可以在Android中使用字符串资源进行代码注释吗?

我可以在 Google Apps Script 中使用字符串句子过滤矩阵或向量吗?

我可以在 kotlin 中使用字符串访问枚举属性吗?

使用 PowerShell 操作对象中的字符串值

使用PowerShell无法将字符串解析为对象

LINQ可以在PowerShell中使用吗?

Powershell 和 .Net。使用字符串创建新类型 - 整数关联

我可以使用 Powershell 从 XML 文件中自动提取具有特定模式的未知字符串并将该字符串写入文本文件吗?

可以使用PowerShell -match运算符来测试版本字符串吗?