powershell 批量AD用户添加到AD组时需要输出到CSV

kuarbcqp  于 2023-05-07  发布在  Shell
关注(0)|答案(1)|浏览(149)

我有一个脚本,将添加多个AD用户到多个AD组。

# Import the data from CSV file and assign it to variable
$List = Import-Csv "C:\Temp\BulkAddGroups.csv"

foreach ($User in $List) {
    # Retrieve UserSamAccountName and ADGroup
    $UserSam = $User.SamAccountName
    $Groups = $User.Group

    # Retrieve SamAccountName and ADGroup
    $ADUser = Get-ADUser -Filter "SamAccountName -eq '$UserSam'" | Select-Object SamAccountName
    $ADGroups = Get-ADGroup -Filter * | Select-Object DistinguishedName, SamAccountName

    # User does not exist in AD
    if ($ADUser -eq $null) {
        Write-Host "$UserSam does not exist in AD" -ForegroundColor Red
        Continue
    }
    # User does not have a group specified in CSV file
    if ($Groups -eq $null) {
        Write-Host "$UserSam has no group specified in CSV file" -ForegroundColor Yellow
        Continue
    }
    # Retrieve AD user group membership
    $ExistingGroups = Get-ADPrincipalGroupMembership $UserSam | Select-Object DistinguishedName, SamAccountName

    foreach ($Group in $Groups.Split(';')) {
        # Group does not exist in AD
        if ($ADGroups.SamAccountName -notcontains $Group) {
            Write-Host "$Group group does not exist in AD" -ForegroundColor Red
            Continue
        }
        # User already member of group
        if ($ExistingGroups.SamAccountName -eq $Group) {
            Write-Host "$UserSam already exists in group $Group" -ForeGroundColor Yellow
        } 
        else {
            # Add user to group
            Add-ADGroupMember -Identity $Group -Members $UserSam
            Write-Host "Added $UserSam to $Group" -ForeGroundColor Green
        }
    }
}

下面是我使用的CSV文件的格式:

我需要在输出到单个CSV文件的行动(无论是成功与否,在添加用户到AD组)的援助。

更新1

@Theo运行了你的代码,得到了这些错误:

Get-ADPrincipalGroupMembership : An unspecified error has occurred
At C:\Users\User\Desktop\BulkAddADGroups.ps1:56 char:31
+             $ExistingGroups = Get-ADPrincipalGroupMembership $UserSam
+                               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (User1:ADPrincipal) [Get-ADPrincipalGroupMembership], ADException
    + FullyQualifiedErrorId : ActiveDirectoryServer:0,Microsoft.ActiveDirectory.Management.Commands.GetADPrincipalGroupMembership
 
Added User1 to Group1
 group does not exist in AD
Get-ADPrincipalGroupMembership : An unspecified error has occurred
At C:\Users\User\Desktop\BulkAddADGroups.ps1:56 char:31
+             $ExistingGroups = Get-ADPrincipalGroupMembership $UserSam
+                               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (User2:ADPrincipal) [Get-ADPrincipalGroupMembership], ADException
    + FullyQualifiedErrorId : ActiveDirectoryServer:0,Microsoft.ActiveDirectory.Management.Commands.GetADPrincipalGroupMembership
 
Added User2 to Group1
 group does not exist in AD
Get-ADPrincipalGroupMembership : An unspecified error has occurred
At C:\Users\User\Desktop\BulkAddADGroups.ps1:56 char:31
+             $ExistingGroups = Get-ADPrincipalGroupMembership $UserSam
+                               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (User3:ADPrincipal) [Get-ADPrincipalGroupMembership], ADException
    + FullyQualifiedErrorId : ActiveDirectoryServer:0,Microsoft.ActiveDirectory.Management.Commands.GetADPrincipalGroupMembership
 
Added User3 to Group1
 group does not exist in AD
Get-ADPrincipalGroupMembership : An unspecified error has occurred
At C:\Users\User\Desktop\BulkAddADGroups.ps1:56 char:31
+             $ExistingGroups = Get-ADPrincipalGroupMembership $UserSam
+                               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (User4:ADPrincipal) [Get-ADPrincipalGroupMembership], ADException
    + FullyQualifiedErrorId : ActiveDirectoryServer:0,Microsoft.ActiveDirectory.Management.Commands.GetADPrincipalGroupMembership
 
Added User4 to Group1
Get-ADPrincipalGroupMembership : An unspecified error has occurred
At C:\Users\User\Desktop\BulkAddADGroups.ps1:56 char:31
+             $ExistingGroups = Get-ADPrincipalGroupMembership $UserSam
+                               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (User4:ADPrincipal) [Get-ADPrincipalGroupMembership], ADException
    + FullyQualifiedErrorId : ActiveDirectoryServer:0,Microsoft.ActiveDirectory.Management.Commands.GetADPrincipalGroupMembership
 
Added User4 to Group2
 group does not exist in AD

我的CSV文件格式是这样的(我按照你的建议使用分号作为分隔符):

我的输出文件是这样的:

我不知道我是不是把;导致该问题的CSV中。
但奇怪的是,用户被添加到了AD组。

更新2

西奥我加了你给我的密码。
MY CSV格式:

再次运行代码得到相同的错误消息:

PS C:\Windows\system32> C:\Users\User\Desktop\BulkAddADGroups.ps1
Get-ADPrincipalGroupMembership : An unspecified error has occurred
At C:\Users\User\Desktop\BulkAddADGroups.ps1:56 char:31
+             $ExistingGroups = Get-ADPrincipalGroupMembership $UserSam
+                               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (User1:ADPrincipal) [Get-ADPrincipalGroupMembership], ADException
    + FullyQualifiedErrorId : ActiveDirectoryServer:0,Microsoft.ActiveDirectory.Management.Commands.GetADPrincipalGroupMembership
 
Added User1 to Group1
Get-ADPrincipalGroupMembership : An unspecified error has occurred
At C:\Users\User\Desktop\BulkAddADGroups.ps1:56 char:31
+             $ExistingGroups = Get-ADPrincipalGroupMembership $UserSam
+                               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (User2:ADPrincipal) [Get-ADPrincipalGroupMembership], ADException
    + FullyQualifiedErrorId : ActiveDirectoryServer:0,Microsoft.ActiveDirectory.Management.Commands.GetADPrincipalGroupMembership
 
Added User2 to Group1
Get-ADPrincipalGroupMembership : An unspecified error has occurred
At C:\Users\User\Desktop\BulkAddADGroups.ps1:56 char:31
+             $ExistingGroups = Get-ADPrincipalGroupMembership $UserSam
+                               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (User3:ADPrincipal) [Get-ADPrincipalGroupMembership], ADException
    + FullyQualifiedErrorId : ActiveDirectoryServer:0,Microsoft.ActiveDirectory.Management.Commands.GetADPrincipalGroupMembership
 
Added User3 to Group1
Get-ADPrincipalGroupMembership : An unspecified error has occurred
At C:\Users\User\Desktop\BulkAddADGroups.ps1:56 char:31
+             $ExistingGroups = Get-ADPrincipalGroupMembership $UserSam
+                               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (User4:ADPrincipal) [Get-ADPrincipalGroupMembership], ADException
    + FullyQualifiedErrorId : ActiveDirectoryServer:0,Microsoft.ActiveDirectory.Management.Commands.GetADPrincipalGroupMembership
 
Added User4 to Group1
Get-ADPrincipalGroupMembership : An unspecified error has occurred
At C:\Users\User\Desktop\BulkAddADGroups.ps1:56 char:31
+             $ExistingGroups = Get-ADPrincipalGroupMembership $UserSam
+                               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (User4:ADPrincipal) [Get-ADPrincipalGroupMembership], ADException
    + FullyQualifiedErrorId : ActiveDirectoryServer:0,Microsoft.ActiveDirectory.Management.Commands.GetADPrincipalGroupMembership
 
Added User4 to Group2

但这次你的输出文件是半正确的:

出于某种原因,输出文件没有为“用户4”选择“组2”的名称,但更奇怪的是,用户实际上被添加到了组中。
在“Group”列中只有一个组名而不是在“Group”列中有多个组有什么价值?
而是像这样:

更新3

太近了!!!
我在PS中运行完美,输出为:

Added User1 to Group1
Added User2 to Group1
Added User3 to Group1
Added User4 to Group1
Added User4 to Group2

它也使AD发生了变化!
但它的CSV输出显示如下:

看起来它没有为用户4输出Group 2,我很高兴保持这一点,只是使用PS提示符的输出,但如果你能得到这个调整,我会很感激。

46qrfjad

46qrfjad1#

查看输入csv,首先按SamAccountName对导入的数据进行分组,然后创建新对象,其中每个用户的所有组都在“Group”列中组合,并以分号作为分隔符。
这样,您也将有机会消除列表中的任何重复项。

# Import the data from CSV file, group on column SamAccountName and 
# output new objects where each item is a single user and all groups for that user
# are separated by a semi-colon in column 'Group'
$List = Import-Csv "C:\Temp\BulkAddGroups.csv" | Group-Object SamAccountName | 
        Select-Object @{Name = 'SamAccountName'; Expression = {$_.Name}},
                      @{Name = 'Group'; Expression = {$_.Group.Group.Split(";").Trim() | 
                                                      Where-Object {$_ -match '\S'} | 
                                                      Sort-Object -Unique}}
# get a list of all AD groups
$ADGroups = Get-ADGroup -Filter *

# capture the (object) output from the loop
$result = foreach ($User in $List) {
    # store the users SamAccountName in a variable for convenience
    $UserSam = $User.SamAccountName

    # User does not have a group specified in CSV file
    if ([string]::IsNullOrWhiteSpace($Groups)) {
        Write-Host "$UserSam has no group specified in CSV file" -ForegroundColor Yellow
        # output an error object
        [PsCustomObject]@{Name = $UserSam; Group = $null; Result = 'Error: User has no group specified in CSV file'}
        Continue  # skip this user an proceed with the next
    }

    # Test if the user exists
    $ADUser = Get-ADUser -Filter "SamAccountName -eq '$UserSam'" -Properties MemberOf

    # User does not exist in AD
    if (!$ADUser) {
        Write-Host "$UserSam does not exist in AD" -ForegroundColor Red
        # output an error object
        [PsCustomObject]@{Name = $UserSam; Group = $null; Result = 'Error: User does not exist in AD'}
        Continue  # skip this user an proceed with the next
    }

    foreach ($Group in @($User.Group)) {
        # create an object to output
        $out = [PsCustomObject]@{
            Name   = $UserSam
            Group  = $Group
            Result = $null    # we'll fill this in later
        }            
        
        # Group does not exist in AD
        if (@($ADGroups).Name -notcontains $Group) {
            Write-Host "$Group group does not exist in AD" -ForegroundColor Red
            # fill the Result property and output the error object
            $out.Result = 'Error: Group does not exist in AD'
        }
        else {
            # Retrieve AD user group membership
            $ExistingGroups = $ADUser.MemberOf | Get-ADGroup | Select-Object Name
            # Get-ADPrincipalGroupMembership is buggy, see
            # https://stackoverflow.com/q/59057379/9898643
            # $ExistingGroups = Get-ADPrincipalGroupMembership $UserSam

            # User is already member of group
            if (@($ExistingGroups).Name -contains $Group) {
                Write-Host "$UserSam already exists in group $Group" -ForeGroundColor Yellow
                # fill the Result property and output the object
                $out.Result = 'Skipped: User is already member'
            } 
            else {
                # Add user to group
                Add-ADGroupMember -Identity $Group -Members $UserSam
                Write-Host "Added $UserSam to $Group" -ForeGroundColor Green
                # fill the Result property and output the object
                $out.Result = 'Success: User added to group'
            }
        }
        # output the object
        $out
    }
}

# now you can save the results in a csv file
$result | Export-Csv -Path 'X:\Somewhere\Results.csv' -NoTypeInformation -UseCulture

屏幕上$result的输出:

Name  Group  Result                      
----  -----  ------                      
User1 Group1 Success: User added to group
User2 Group1 Success: User added to group
User3 Group1 Success: User added to group
User4 Group1 Success: User added to group
User4 Group2 Success: User added to group

相关问题