Creating AD users using a CSV file and a splat

6 views
Skip to first unread message

Mike Leone

unread,
Apr 16, 2025, 3:56:14 PMApr 16
to NTPowershell Mailing List
My co-worker is starting to learn PS. And he's trying to bulk create users from a CSV file. And it's failing. Looks like it should work, to me. What are we missing?

#Import active directory module for running AD cmdlets
#Author: Darnell Brooks

Import-Module activedirectory

#Store the data from ADUsers.csv in the $ADUsers variable
$Users = Import-csv "C:\Temp\AD UserBulkTest.csv"

#Loop through each row containing user details in the CSV file
foreach ($User in $Users) {
    # Read user data from each field in each row
    # the username is used more often, so to prevent typing, save that in a variable
   $Username       = $User.SamAccountName

    # Check to see if the user already exists in AD
    if (Get-ADUser -F {SamAccountName -eq $Username}) {
         #If user does exist, give a warning
         Write-Warning "A user account with username $Username already exist in Active Directory."
    }
    else {
        # User does not exist then proceed to create the new user account

        # create a hashtable for splatting the parameters
        $userProps = @{
            SamAccountName             = $User.SamAccountName              
            Path                       = $User.Path      
            GivenName                  = $User.GivenName
            Surname                    = $User.Surname
            Initials                   = $User.Initials
            Name                       = $User.Name
            DisplayName                = $User.DisplayName
            Description                = $User.Description
            EmailAddress               = $User.EmailAddress
            AccountPassword            = (ConvertTo-SecureString $User.Password -AsPlainText -Force)
            Enabled                    = $true
            ChangePasswordAtLogon      = $true
        }   #end userprops  

         New-ADUser @userProps
       #  Write-Host "The user account $User is created." -ForegroundColor Cyan
   

    } #end else
   
}

When we run it, it errors out:

S O:\software\PHA Scripts\1 - Test> .\BulkAddUser-test.ps1
New-ADUser : Directory object not found
At O:\software\PHA Scripts\1 - Test\BulkAddUser-test.ps1:39 char:10
+          New-ADUser @userProps
+          ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (CN=John Doe,OU=...DC=phila,DC=Gov:String) [New-ADUser], ADIdentityNotFoundException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.
   NewADUser

The splat looks correct, it's being populated correctly, from what I can see. So why is it failing?
I know it's something simple, but what?

--

Mike. Leone, <mailto:tur...@mike-leone.com>

PGP Fingerprint: 0AA8 DC47 CB63 AE3F C739 6BF9 9AB4 1EF6 5AA5 BCDF
Photo Gallery: <http://www.flickr.com/photos/mikeleonephotos>

Solodow, Damien

unread,
Apr 16, 2025, 4:06:36 PMApr 16
to ntpowe...@googlegroups.com

I’m leaning towards it being an issue with the $user.Path part; basically it can’t find the location you’re trying to create the user in.

Is that path the container that the user should be created in?

 

Gaylor Electric logo

Gaylor Electric Website

Facebook

Twitter

LinkedIn

Damien Solodow
IT Senior Systems Engineer
Gaylor Electric, Inc.
10405 Crosspoint Blvd
Indianapolis, IN. 46256
O: 317.815.3103 | M: 317.506.8521

--
You received this message because you are subscribed to the Google Groups "ntpowershell" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ntpowershell...@googlegroups.com.
To view this discussion visit https://groups.google.com/d/msgid/ntpowershell/CAHBr%2B%2BiSK7yWe0sCd%2BpHxwgd%3DMxw4T4KnxYH0SGoJ9Hg6ify3A%40mail.gmail.com.

Michael B. Smith

unread,
Apr 16, 2025, 4:11:58 PMApr 16
to ntpowe...@googlegroups.com

I tend to agree.

 

The basic code looks ok, but without sample data, it’s impossible to be sure.

Wright, John M

unread,
Apr 16, 2025, 4:17:15 PMApr 16
to ntpowe...@googlegroups.com

I don’t usually create users this way, but I was checking the help file on New-ADUser and noticed this:

 

The following example shows how to set this parameter to an OU.

 

        -Path "ou=mfg,dc=noam,dc=corp,dc=contoso,dc=com"

 

There’s no username in that.  But your error looks like it includes it.  Does the path property terminate at the destination OU or with the username?

 

ObjectNotFound: (CN=John Doe,OU=...DC=phila,DC=Gov:String) [New-ADUser], ADIdentityNotFoundException

 

--

John Wright

IT Support Specialist

1800 Old Bluegrass Avenue, Louisville, KY 40215

502.708.9953

Please submit IT requests to Hazelwoo...@bluegrass.org

24 Hour Helpline 1.800.928.8000

  

CONFIDENTIALITY NOTICE: This message contains confidential information and is intended only for the individual(s) addressed in the message. If you are not the named addressee, you should not disseminate, distribute, or copy this e-mail. If you are not the intended recipient, you are notified that disclosing, distributing, or copying this e-mail is strictly prohibited.

 

From: ntpowe...@googlegroups.com <ntpowe...@googlegroups.com> On Behalf Of Mike Leone
Sent: Wednesday, April 16, 2025 3:56 PM
To: NTPowershell Mailing List <ntpowe...@googlegroups.com>
Subject: [ntpowershell] Creating AD users using a CSV file and a splat

 

EXTERNAL EMAIL - This email was sent by a person from outside your organization. Exercise caution when clicking links, opening attachments or taking further action, before validating its authenticity.

Secured by Check Point

--

Michael B. Smith

unread,
Apr 16, 2025, 4:19:37 PMApr 16
to ntpowe...@googlegroups.com

Should contain just the OU.

 

From: ntpowe...@googlegroups.com <ntpowe...@googlegroups.com> On Behalf Of Wright, John M


Sent: Wednesday, April 16, 2025 4:17 PM
To: ntpowe...@googlegroups.com

Michael B. Smith

unread,
Apr 16, 2025, 4:42:15 PMApr 16
to ntpowe...@googlegroups.com

A slightly simpler example that I know works. It has some details left out, but I’m sure you can figure it out. 😊

 

Notice that I cheat – if your CSV file headers are exactly the same as the parameters to New-ADUser, you don’t have to create a separate hashtable. So $u is a line from the CSV.

 

(One hint: wv stands for ‘write-verbose’)

 

    $sam   = $u.SamAccountName

    $disp  = $u.DisplayName

    $email = $u.EmailAddress

 

    $user = Get-ADUser -LDAPFilter "(samaccountname=$sam)" -EA 0

    if( $null -ne $user )

    {

        wv "User already exists in AD: sam='$sam' displayname='$disp' email='$email'"

    }

    else

    {

        wv "User does NOT exist in AD, will create: sam='$sam' displayname='$disp' email='$email'"

        $path = 'OU=NoGP,OU=RegularUsers,DC=contoso,DC=Com'

        New-ADUser @u -AccountPassword $secure -Path $path -ChangePasswordAtLogon $false

        if( $? )

        {

            wv "User successfully created"

        }

        else

        {

            wv "User creation FAILED. User index $( $count - 1 ), UPN '$( $u.UserPrincipalName )', SAM '$( $u.SamAccountName )', Display '$( $u.DisplayName )', error '$( $error[ 0 ] )'"

Reply all
Reply to author
Forward
0 new messages