views:

56

answers:

1

Hey guys, this one is out there for the PS gurus. I've created a script that reads from a CSV (or other dataset, but not posting that side) and creates users in my AD environment.

Basically, whatever dataset is passed into the script will be processed, and then a user will be created if they do not exist. If the user exists in the AD already, then the script skips over the entry. This is a CREATE only script.

It's pretty slow, and I'd like to improve the performance whilst keeping the functionality. Can you give me any tips as to how I can make this perform better?

import-csv "c:\PSScripts\LDAP\ADMigrate.csv" | ForEach-Object {

# Define the User OU 
$usersOU = [ADSI] "LDAP://ou=Students, dc=live,dc=tcicollege,dc=edu"

# Check for existing users
$existingUsers = ($usersOU.psbase.children | Where-Object {$_.psBase.schemaClassName -eq "User"} | Select-Object -expand Name)
$userQuery = $existingUsers -contains $_.'AccountName'
if ($userQuery) {
    echo $_.'AccountName' " already exists in Directory."
} else {

    # Create a new user
    $newUser = $usersOU.create("user","cn=" + $_.'AccountName')

    # Set Account AttributesAMAccountName 
    $newUser.Put("sAMAccountName", $_.'AccountName')
    $newUser.Put("givenName", $_.'FirstName')
    $newUser.Put("employeeID", $_.'StudentID')
    $newUser.Put("sn", $_.'LastName')
    $newUser.Put("department", $_.'Department')
    $newUser.Put("company", $_.'SyStudentID')
    $newUser.Put("UserPrincipalName", $_.'AccountName' + "@live.tcicollege.edu")
    $newUser.Put("mail", $_.'AccountName' + "@live.tcicollege.edu")
    $newUser.Put("displayName", $_.'LastName' + "," + " " + $_.'FirstName')

    # First Commit
    $newUser.SetInfo()
    $newUser.userAccountControl="66048"
    $newUser.Put("pwdLastset", -1)
    $newUser.SetPassword($_.'Password')

    # Final Commit
    $newUser.SetInfo()
    echo $_.'AccountName' " created successfully."
  }
}

Thank you in advance for any help you can offer.

+2  A: 

Try the static Exists() method to find if the user exists in the Students OU:

$user = [ADSI]::Exists "LDAP://cn=$($_.AccountName),ou=Students, dc=live,dc=tcicollege,dc=edu" if(!$user)
{
"create code goes here"
}

The $usersOU value is static so you can take it out, place it before the import-csv command.

Shay Levy
That's a very interesting idea-- that processes on the LDAP level, instead of querying against the LDAP response, right? I'll implement it ASAP on one of the dev nodes and let you know how that works. I don't want to mark as answer yet-- if this significantly improves the performance, I definitely will.Thank you for the suggestion! I don't like the ADSI interface in PS. Or period, even.
Buzzedword
np :) BTW, Quest has a free set of cmdlets to manage your AD, check it out: http://www.quest.com/powershell/activeroles-server.aspx
Shay Levy
This worked just fine for me. Thanks!
Buzzedword