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

标签 powershell active-directory csv ldap adsi

我创建了一个从 CSV(或其他数据集,但不发布该侧)读取的脚本,并在我的 AD 环境中创建用户。
基本上,任何传递到脚本中的数据集都会被处理,然后如果它们不存在就会创建一个用户。如果该用户已存在于 AD 中,则脚本将跳过该条目。这是一个仅创建脚本。
它非常慢,我想在保持功能的同时提高性能。你能给我一些关于如何让这个表现更好的提示吗?

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."
  }
}
预先感谢您提供的任何帮助。

最佳答案

尝试静态 Exists() 方法以查找用户是否存在于学生 OU 中:

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

$usersOU 值是静态的,因此您可以将其取出,放在 import-csv 命令之前。

关于powershell - 如何优化我的 PowerShell - LDAP 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3072800/

相关文章:

powershell - 在工作流旁边使用递归函数

powershell - 在Powershell 2.0中无法将 “PasswordNeverExpires”参数设置为true

python - 从 RapidMiner Studio 中的执行 Python 处理器返回 pandas DataFrame 时出现 ValueError

python - 如何在 Excel 中为文件夹中的每个 csv 文件创建新工作表

C++ CSV 行,双引号内有逗号和字符串

function - 使用多个参数从.ps1运行PowerShell的函数

powershell - 无法使用Get-MessageTrackingLog作为Sender@domain.com.CSV导出外部电子邮件收件人的列表?

powershell - 如何使用Invoke-RestMethod上传jpg

active-directory - 身份服务器和 ADFS

c# - 这段异步代码有什么问题?