开发者

How can I optimize my PowerShell - LDAP Query?

开发者 https://www.devze.com 2023-01-03 19:35 出处:网络
I have created a script that reads from a CSV (or other dataset, but not posting that side) and creates users in my AD environment.

I have 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消