title: How can I optimize my PowerShell - LDAP Query?
body: <p>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.</p>
  <p>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.</p>
  <p>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?</p>
  <pre><code>import-csv &quot;c:\PSScripts\LDAP\ADMigrate.csv&quot; | ForEach-Object {
  
  # Define the User OU 
  $usersOU = [ADSI] &quot;LDAP://ou=Students, dc=live,dc=tcicollege,dc=edu&quot;
  
  # Check for existing users
  $existingUsers = ($usersOU.psbase.children | Where-Object {$_.psBase.schemaClassName -eq &quot;User&quot;} | Select-Object -expand Name)
  $userQuery = $existingUsers -contains $_.'AccountName'
  if ($userQuery) {
      echo $_.'AccountName' &quot; already exists in Directory.&quot;
  } else {
  
      # Create a new user
      $newUser = $usersOU.create(&quot;user&quot;,&quot;cn=&quot; + $_.'AccountName')
  
      # Set Account AttributesAMAccountName 
      $newUser.Put(&quot;sAMAccountName&quot;, $_.'AccountName')
      $newUser.Put(&quot;givenName&quot;, $_.'FirstName')
      $newUser.Put(&quot;employeeID&quot;, $_.'StudentID')
      $newUser.Put(&quot;sn&quot;, $_.'LastName')
      $newUser.Put(&quot;department&quot;, $_.'Department')
      $newUser.Put(&quot;company&quot;, $_.'SyStudentID')
      $newUser.Put(&quot;UserPrincipalName&quot;, $_.'AccountName' + &quot;@live.tcicollege.edu&quot;)
      $newUser.Put(&quot;mail&quot;, $_.'AccountName' + &quot;@live.tcicollege.edu&quot;)
      $newUser.Put(&quot;displayName&quot;, $_.'LastName' + &quot;,&quot; + &quot; &quot; + $_.'FirstName')
  
      # First Commit
      $newUser.SetInfo()
      $newUser.userAccountControl=&quot;66048&quot;
      $newUser.Put(&quot;pwdLastset&quot;, -1)
      $newUser.SetPassword($_.'Password')
  
      # Final Commit
      $newUser.SetInfo()
      echo $_.'AccountName' &quot; created successfully.&quot;
    }
  }
  </code></pre>
  <p>Thank you in advance for any help you can offer.</p>