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

问题描述 投票:0回答:1

我有一个脚本可以将多个 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文件格式:

我需要帮助将操作(无论是否成功将用户添加到 AD 组)输出到单个 CSV 文件中。

更新 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

Theo 我添加了你给我的代码。

我的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”的名称,但它变得更加奇怪,用户实际上被添加到组中。

在“组”列中使用单个组名而不是在“组”列中使用多个组有什么意义?

像这样:

更新 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 输出 Group2,我很乐意保留它并只使用 PS 提示符的输出,但如果你能对此进行调整,我将不胜感激。

powershell automation export-to-csv
1个回答
1
投票

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

# 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
© www.soinside.com 2019 - 2024. All rights reserved.