简体   繁体   English

如何优化我的 PowerShell - LDAP 查询?

[英]How can I optimize my PowerShell - LDAP Query?

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.我创建了一个从 CSV(或其他数据集,但不发布该侧)读取的脚本,并在我的 AD 环境中创建用户。

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.如果该用户已存在于 AD 中,则脚本将跳过该条目。 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:尝试静态 Exists() 方法以查找用户是否存在于学生 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. $usersOU 值是静态的,因此您可以将其取出,放在 import-csv 命令之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM