创建新的AD用户并将其从CSV添加到多个组

时间:2019-01-28 10:50:36

标签: powershell active-directory

我已经承担了创建学校用户数量的任务(英国中学)。 PS通过CSV创建用户,我需要做的是将新创建的用户同时添加到各个组中。

我使用的代码如下

public void createPdf(View v) {
    PDDocument document = new PDDocument();
    PDPage page = new PDPage();
    document.addPage(page);

    // Create a new font object selecting one of the PDF base fonts
    PDFont font = PDType1Font.HELVETICA;
    // Or a custom font
    //try {
    //  PDType0Font font = PDType0Font.load(document, assetManager.open("MyFontFile.TTF"));
    //} catch(IOException e) {
    //  e.printStackTrace();
    //}

    PDPageContentStream contentStream;

    try {
        // Define a content stream for adding to the PDF
        contentStream = new PDPageContentStream(document, page);

        String preText = "Icons made by ";
        String linkText = "My_Site";

        float upperRightX = page.getMediaBox().getUpperRightX();
        float upperRightY = page.getMediaBox().getUpperRightY();
        // Write linkText in blue text
        contentStream.beginText();
        contentStream.setNonStrokingColor(15, 38, 192);
        contentStream.setFont(font, 18);
        contentStream.moveTextPositionByAmount( 0, upperRightY-20);
        contentStream.drawString(preText + linkText);
        contentStream.endText();

        // create a link annotation
        PDAnnotationLink txtLink = new PDAnnotationLink();

        // set up the markup area
        float offset = (font.getStringWidth(preText) / 1000) * 18;
        float textWidth = (font.getStringWidth(linkText) / 1000) * 18;
        PDRectangle position = new PDRectangle();
        position.setLowerLeftX(offset);
        position.setLowerLeftY(upperRightY - 24f);
        position.setUpperRightX(offset + textWidth);
        position.setUpperRightY(upperRightY -4);
        txtLink.setRectangle(position);

        // add an action
        PDActionURI action = new PDActionURI();
        action.setURI("https://www.**********.com/");
        txtLink.setAction(action);

        // and that's all ;-)
        page.getAnnotations().add(txtLink);

        // load 'Social media' icons from 'vector' resources.
        float padding = 5, startX = 5, startY = upperRightY-100, width = 25, height=25;
        loadVectorIconWithLink(document, page, contentStream, R.drawable.ic_facebook,
                "https://www.facebook.com/My_Name/", startX, startY, width, height);
        startX += (width + padding);
        loadVectorIconWithLink(document, page, contentStream, R.drawable.ic_instagram,
                "https://www.instagram.com/My_Name", startX, startY, width, height);

        // Make sure that the content stream is closed:
        contentStream.close();

        // Save the final pdf document to a file
        String path = root.getAbsolutePath() + "/Download/Created.pdf";
        document.save(path);
        document.close();
        tv.setText("Successfully wrote PDF to " + path);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

private void loadVectorIconWithLink( PDDocument theDocument,
                                     PDPage thePage,
                                     PDPageContentStream theContentStream,
                                     @DrawableRes int theDrawableId,
                                     String theUriString,
                                     float x, float y, float width, float height
                                     ) throws IOException
{
    Bitmap alphaImage = getBitmapFromDrawable(this, theDrawableId);
    PDImageXObject alphaXimage = LosslessFactory.createFromImage(theDocument, alphaImage);
    theContentStream.drawImage(alphaXimage, x, y, width, height );

    // create a link annotation
    PDAnnotationLink iconLink = new PDAnnotationLink();
    PDRectangle position = new PDRectangle( x, y, width, height );
    iconLink.setRectangle(position);

    // add an action
    PDActionURI action1 = new PDActionURI();
    action1.setURI(theUriString);
    iconLink.setAction(action1);

    // and that's all ;-)
    thePage.getAnnotations().add(iconLink);
}

public static Bitmap getBitmapFromDrawable(Context context, @DrawableRes int drawableId) {
    Drawable drawable = AppCompatResources.getDrawable(context, drawableId);

    if (drawable instanceof BitmapDrawable) {
        return ((BitmapDrawable) drawable).getBitmap();
    } else if (drawable instanceof VectorDrawableCompat || drawable instanceof VectorDrawable) {
        Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);

        return bitmap;
    } else {
        throw new IllegalArgumentException("unsupported drawable type");
    }
}

创建具有正确设置所有属性的用户。失败并显示以下错误

$DCName = '<DC FQDN>'

Import-Csv -Path "D:\Import.csv" |

ForEach-Object {
    $Displayname = $_.'FirstName' + " " + $_.'LastName'
    $UPN = $_.'UPN'
    $GroupName = $_.'GroupName'
    $Prop = @{
        Name = $Displayname
        DisplayName = $_.'FirstName' + " " + $_.'LastName'
        GivenName = $_.'FirstName' 
        Surname = $_.'LastName' 
        UserPrincipalName = $UPN 
        EmailAddress = $UPN 
        SamAccountName = $_.'SAM' 
        AccountPassword = (ConvertTo-SecureString $_.'Password' -AsPlainText -Force) 
        Enabled = $true 
        Path = $_.'OU' 
        ChangePasswordAtLogon = $false 
        Title = $_.'JobTitle' 
        StreetAddress = $_.'Street' 
        City = $_.'Town' 
        State = $_.'County'
        PostalCode = $_.'PostCode' 
        OfficePhone = $_.'Telephone' 
        Company = $_.'Company' 
        Department = $_.'Department' 
        HomeDrive = $_.'HomeDrive' 
        HomeDirectory = $_.'Home-Directory' 
        OtherAttributes = @{
            'extensionAttribute1'= $_.'ExtendedAttribute1'; 
            'extensionAttribute2'= $_.'ExtendedAttribute2'; 
            'extensionAttribute14'= $_.'ExtendedAttribute14'; 
            'extensionAttribute15'= $_.'ExtendedAttribute15'; 
            'proxyAddresses' = "SMTP:" + $UPN;} 
        Server = $DCName

        }

         New-ADUser @prop

         Add-ADGroupMember -Identity $GroupName -Members $_.'SAM'

}

看来,Add-ADGroupMember命令无法找到刚刚创建的用户,但是,如果是这种情况,我不明白为什么。

目前,我的CSV在“ GroupName”中只有一个组,将用户添加到多个组的最佳方法是什么?例如全校员工,教职员工,科学老师等。

在此先感谢您提供的任何帮助。

2 个答案:

答案 0 :(得分:1)

由于它是批量操作,因此我将用户创建与组成员身份分开。

首先创建所有用户,然后将它们添加到组中:

$DCName = '<DC FQDN>'
$Users = Import-Csv -Path "D:\Import.csv"

$Users | ForEach-Object {
    $Displayname = $_.'FirstName' + " " + $_.'LastName'
    $UPN = $_.'UPN'

    $Prop = @{
        ## properties as per original code ##
    }

    New-ADUser @prop
}

$Users | ForEach-Object {
    $GroupName = $_.'GroupName'
    Add-ADGroupMember -Identity $GroupName -Members $_.'SAM'    
}

用于将用户添加到多个组的:

如果您在GroupName中有分号分隔的组列表,例如

School-All-Staff;Teaching-Staff;Science-Teachers

Split会将其转换为数组,然后您可以遍历它们:

$_.'GroupName' -split ';' | ForEach-Object {
    Add-ADGroupMember $_ –Member $user.'SAM'
}

(编辑:当您有csv源时,更新为分号)

答案 1 :(得分:0)

最后,我将其作为组合脚本工作,并为先前存在的用户添加了错误检查功能,现有员工通常会在将其添加到我们的AD中之前,先将其添加到Trust中添加的新学校。在要创建的用户列表中。

还添加了日志文件创建功能,以记录新创建的用户并列出其SAMAccount名称已经存在的用户,以便我们检查用户是否确实需要创建或是否需要从另一个School OU迁移。

这是我的最终代码:

#Get deafult variables to tidy up created variables at the end
$ExistingVariables = Get-Variable | Select-Object -ExpandProperty Name

#New User Code Starts Here>

#Variables not set by CSV

#Set DC name to update - prevents errors due to replication delay
$DCName = '<DC FQDN>'

#Create log files
"Users Exist in AD" | Out-File -FilePath "D:\Logs\ExistingUsers-$(get-date -f yyyyMMdd).txt" -Append
"New Users Created" | Out-File -FilePath "D:\Logs\NewUsers-$(get-date -f yyyyMMdd).txt" -Append

#Specify path and file to import
Import-Csv -Path "D:\Import.csv" |

#Iterate through each row in the CSV
ForEach-Object {

    #Set per object variables from fields in the CSV
    $DisplayName = $_.'FirstName' + " " + $_.'LastName'
    $UPN = $_.'UPN'
    $GroupName1 = $_.'GroupName1'
    $GroupName2 = $_.'GroupName2'
    $GroupName3 = $_.'GroupName3'
    $GroupName4 = $_.'GroupName4'
    $SAM = $_.'SAM'
    $Password = $_.'Password'
    $SAMTest = Get-ADUser -Filter {(sAMAccountName -eq $SAM)} -Server $DCName

    #Splatting Hash Table holds all user attribute properties set in the CSV
    $Prop = @{
        Name = $DisplayName
        DisplayName = $DisplayName
        GivenName = $_.'FirstName' 
        Surname = $_.'LastName' 
        UserPrincipalName = $UPN 
        EmailAddress = $UPN 
        SamAccountName = $_.'SAM' 
        AccountPassword = (ConvertTo-SecureString $_.'Password' -AsPlainText -Force) 
        Enabled = $true 
        Path = $_.'OU' 
        ChangePasswordAtLogon = $false 
        Title = $_.'JobTitle' 
        StreetAddress = $_.'Street' 
        City = $_.'Town' 
        State = $_.'County'
        PostalCode = $_.'PostCode' 
        OfficePhone = $_.'Telephone' 
        Company = $_.'Company' 
        Department = $_.'Department' 
        OtherAttributes = @{
            'extensionAttribute1'= $_.'ExtendedAttribute1'; 
            'extensionAttribute2'= $_.'ExtendedAttribute2'; 
            'extensionAttribute14'= $_.'ExtendedAttribute14'; 
            'extensionAttribute15'= $_.'ExtendedAttribute15'; 
            'proxyAddresses' = "SMTP:" + $UPN;} 
        Server = $DCName

        }


    #Check if SAMAccount name exists in AD and skip existing users
    if ($SAMTest -ne $Null)
        {
        #Get UPN property of the pre-existing user
        $Exist = Get-ADUser -Filter {(sAMAccountName -eq $SAM)} -Properties 'userprincipalname'

        #write UPN value to variable
        $ExistUPN = $Exist.userprincipalname

        #Update log of pre-existing users
        "$DisplayName exists with email $ExistUPN" | Out-File -FilePath "D:\Logs\ExistingUsers-$(get-date -f yyyyMMdd).txt" -Append

        #Write to screen
        Write-Host "$DisplayName already exists in AD" -ForegroundColor Red

        }
    else
        {
        #Create new user with the attribute properties collected above
        New-ADUser @prop

        #Check if group fields in CSV were populated, if true add user to group, if false skip                  
        if ($_.'GroupName1'){Add-ADGroupMember -Identity $_.'GroupName1' -Members $_.'SAM' -Server $DCName}

        if ($_.'GroupName2'){Add-ADGroupMember -Identity $_.'GroupName2' -Members $_.'SAM' -Server $DCName}

        if ($_.'GroupName3'){Add-ADGroupMember -Identity $_.'GroupName3' -Members $_.'SAM' -Server $DCName}

        if ($_.'GroupName4'){Add-ADGroupMember -Identity $_.'GroupName4' -Members $_.'SAM' -Server $DCName} 

        #Update New user log 
        "$UPN" | Out-File -FilePath "D:\Logs\NewUsers-$(get-date -f yyyyMMdd).txt" -Append

        #Write to screen
        Write-Host "User $SAM created at $((Get-Date).ToString('hh:mm'))" -ForegroundColor Green

        }
}

#End Of New User Code

#Remove variables set by script - keeps PS memory space tidy
$NewVariables = Get-Variable | Select-Object -ExpandProperty Name | Where-Object {$ExistingVariables -notcontains $_ -and $_ -ne "ExistingVariables"}
if ($NewVariables)
    {
    Write-Host "Removing the following variables:`n`n$NewVariables"
    Remove-Variable $NewVariables
    }
else
    {
    Write-Host "No new variables to remove!"
    }

我花了一些时间来清理变量,因为如果PowerShell会话保持打开状态并且导致奇怪的事情发生,那么值似乎会持续存在。我还删除了主驱动器属性,因为指定的文件服务器尚未实现,但管理层现在仍希望AD中的用户。

作为参考,我的import.csv看起来像这样

FirstName,LastName,UPN,SAM,Password,OU,JobTitle,Street,Town,County,PostCode,Telephone,Company,Department,ExtendedAttribute1,ExtendedAttribute2,ExtendedAttribute14,ExtendedAttribute15,GroupName1,GroupName2,GroupName3,GroupName4
Test,User,Test.Users@domain.uk,Test.User,,"OU=Admin Staff,OU=User Resources,OU=School,OU=Trust Schools,DC=AD,DC=Trust,DC=org",,Street Name,TownName,County,AA11 1AA,116123,Name Of School,Name Of Trust,,Staff,,,AllStaffGroup,AdminStaffGroup,SpecialPermissionsGroup,Group4
相关问题