PowerShell 通过 CSV 将用户添加到 AD 组 - 脚本不添加用户

PowerShell Add users to AD group via CSV - script not adding users

>     # Start transcript Start-Transcript -Path C:\Temp\Add-ADUsers.log -Append
> 
> # Import AD Module Import-Module ActiveDirectory
> 
> # Import the data from CSV file and assign it to variable $Users = Import-Csv "C:\Temp\jacktest.csv"
> 
> # Specify target group where the users will be added to
> # You can add the distinguishedName of the group. For example: CN=Pilot,OU=Groups,OU=Company,DC=exoip,DC=local $Group = "JackTest" 
> 
> foreach ($User in $Users) {
>     # Retrieve UPN
>     $UPN = $User.UserPrincipalName
> 
>     # Retrieve UPN related SamAccountName
>     $ADUser = Get-ADUser -Filter "UserPrincipalName -eq '$UPN'" | Select-Object SamAccountName
> 
>     # User from CSV not in AD
>     if ($ADUser -eq $null) {
>         Write-Host "$UPN does not exist in AD" -ForegroundColor Red
>     }
>     else {
>         # Retrieve AD user group membership
>         $ExistingGroups = Get-ADPrincipalGroupMembership $ADUser.SamAccountName | Select-Object Name
> 
>         # User already member of group
>         if ($ExistingGroups.Name -eq $Group) {
>             Write-Host "$UPN already exists in $Group" -ForeGroundColor Yellow
>         }
>         else {
>             # Add user to group
>             Add-ADGroupMember -Identity $Group -Members $ADUser.SamAccountName -WhatIf
>             Write-Host "Added $UPN to $Group" -ForeGroundColor Green
>         }
>     } } Stop-Transcript

代码未成功将用户添加到组 我正在尝试将 900 多个用户添加到标题为“UserPrincipalName”的 CSV 广告组 报告 else if 语句按预期工作。

我认为您的代码已经足够好了,我认为没有更改的原因是 -WhatIf 开关,它应该显示一条消息而不是执行操作。

除此之外,您可以考虑几件事,其中之一是 | Select-object 这会将对象修改为 PSCustomObject,您将失去拥有 ADObject。 另一件事是你使用的比较,而不是 -eq 你最好使用 -contains 的列表,所以你得到 true/false 。 第三但并非最不重要的是与 $null 的比较,在那种特殊情况下我认为你并不真的需要它,但你宁愿只看看是否返回了 (-not $ADUser)

考虑到所有这些,我已根据我的评论修改代码。

foreach ($User in $Users) {
    # Retrieve UPN
    $UPN = $User.UserPrincipalName

    # Retrieve UPN related SamAccountName
    $ADUser = Get-ADUser -Filter "UserPrincipalName -eq '$UPN'"

    # User from CSV not in AD
    if (-not $ADUser) {
        Write-Host "$UPN does not exist in AD" -ForegroundColor Red
    }
    else {
        # Retrieve AD user group membership
        $ExistingGroups = Get-ADPrincipalGroupMembership $ADUser.SamAccountName

        # User already member of group
        if ($ExistingGroups.Name -contains $Group) {
            Write-Host "$UPN already exists in $Group" -ForeGroundColor Yellow
        }
        else {
            # Add user to group
            Add-ADGroupMember -Identity $Group -Members $ADUser.SamAccountName
            Write-Host "Added $UPN to $Group" -ForeGroundColor Green
        }
    } 
} Stop-Transcript