PowerShell - 将新用户添加到AD组的选择中

时间:2016-03-08 02:31:02

标签: powershell active-directory powershell-v2.0

我创建了一个表单来创建新的AD帐户。脚本的一部分根据下一个代码中以下拉选择框形式捕获的角色(医生,护士,管理员或其他)确定新用户将添加到哪些组:

Write-Host "Based on this information" $FFN "has been added to the following Active Directory Groups:"
Write-Host 

$ADGroup01 = Get-ADGroup "_XA_App_XenApp" |select -expandproperty name -first 1
Write-Host $ADGroup01
$ADGroup02 = Get-ADGroup "Web Proxy Users" |select -expandproperty name -first 1
Write-Host $ADGroup02
if($RadioButton1.Checked -eq $true)
    {
    $ADGroup03 = Get-ADGroup "allrot" |select -expandproperty name -first 1
    Write-Host $ADGroup03
    }
Else
    {
    $ADGroup03 = Get-ADGroup "alltpo" |select -expandproperty name -first 1
    Write-Host $ADGroup03
    }
if ($Role -eq "Doctor" -Or $Role -eq "Nurse")
    {
    $ADGroup04 = Get-ADGroup "PACS Web Access" |select -expandproperty name -first 1
    Write-Host $ADGroup04
    }
if ($Role -eq "Doctor")
    {
    $ADGroup05 = Get-ADGroup "CH-MFD" |select -expandproperty name -first 1
    Write-Host $ADGroup05
    $ADGroup06 = Get-ADGroup "ED-MFP" |select -expandproperty name -first 1
    Write-Host $ADGroup06
    $ADGroup07 = Get-ADGroup "SU-MFD" |select -expandproperty name -first 1
    Write-Host $ADGroup07
    }
Write-Host 

在脚本中,在实际的帐户创建过程中会调用这段代码:

Add-ADPrincipalGroupMembership -Identity $UN -memberof $ADGroup01, $ADGroup02, $ADGroup03, $ADGroup04, $ADGroup05, $ADGroup06, $ADGroup07

我面临的问题是,如果用户选择护士,管理员或其他,我会收到以下错误:

" Add-ADPrincipalGroupMembership:无法验证参数' MemberO的参数 F&#39 ;.参数为null,空或参数集合的元素 输入空值。提供不包含任何空值的集合  然后再次尝试命令。"

我知道这是因为在最后的$ ADGroup [x]中没有捕获值,也没有创建一堆if语句来检查每个$ ADGroup是否包含数据我想知道是否还有更多优雅的解决方案。

与往常一样,感谢您抽出时间进行审核,并乐意在必要时提供更多信息。

更新 - 根据@ Martin的建议,我已在我的脚本中实现了以下代码

$UN = "zooz"
$Role = "Nurse"
$Department = "Surgical"

If ($Role -eq "Doctor" -and $Department -eq "Surgical")
{
$ADGroups = @(
"PACS Web Access"
"CH-MFD"
"ED-MFP"
"SU-MFD"
)
}

If ($Role -eq "Nurse" -and $Department -eq "Surgical")
{
$ADGroups = @(
"_XA_App_XenApp"
"Web Proxy Users"
"allrot"
)
}

for ($i=0; $i -lt $ADGroups.length; $i++) {
Add-ADPrincipalGroupMembership -Identity $UN -memberof $adgroups[$i] 
}

1 个答案:

答案 0 :(得分:0)

创建一个对象$adgroups并将所需的组添加到其中。

$adgroups = @()

最后使用foreach循环:

$adgroups | Add-ADPrincipalGroupMembership -Identity $UN或(天气或非cmdlet喜欢流水线输入)

$adgroups | % { Add-ADPrincipalGroupMembership -Identity $UN -memberof $_ }