拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 PowerShell通过CSV将用户添加到AD组-脚本不添加用户

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

白鹭 - 2022-01-26 2172 0 0
>     # 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 多个用户从 CSV 添加到带有标题“UserPrincipalName”的 AD 组 如果陈述句按预期作业,则报告 else。

uj5u.com热心网友回复:

我认为您的代码足够好,我认为没有进行更改的原因是-WhatIfswitch ,它应该显示一条讯息而不是执行操作。

除此之外,您还可以考虑几件事,一个是| Select-objectthis 会将物件修改为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
标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *