none
New-ADUser : The object name has bad syntax RRS feed

  • Question

  • I am trying to pull information from a .CSV file to create AD Users in this same script I am trying to pull the OU from the parent user listed on the CSV file. However for the life of me I can not get this thing to run without giving me the same error each time. i have checked for blank spaces and I don' see anything that would suggest that it's wrong can someone lend me their knowledge on the matter?

    # Import active directory module for running AD cmdlets
    Import-Module activedirectory
      
    #Store the data from ADUsers.csv in the $ADUsers variable
    $ADUsers = Import-csv C:\PScripts\UsersToCreate.csv
    
    #Loop through each row containing user details in the CSV file 
    foreach ($User in $ADUsers)
    {
        #Read user data from each field in each row and assign the data to a variable as below
        $Username = $User.SamAccountName 
        $SamAccountName = $Firstname.Substring(0,1) + $Lastname
        $Password = $User.Password
        $Firstname = $User.FirstName
        $Lastname = $User.LastName
        $email = $User.Email
        $OfficePhone = $User.Office
        $Mobile = $User.Mobile
        $jobtitle = $User.Title
        $company = $User.Company
        $department = $User.Department
        $Password = $User.Password
        $Manager = $User.Manager
        $DisplayName = $User.Displayname
        $UserToCopy = $User.UserToCopy
        $DN = $User.distinguishedName
        $OldUser = [ADSI]"LDAP://$DN"
        $Parent = $OldUser.Parent
        $OU = [ADSI]$Parent
        $OUDN = $OU.distinguishedName
    
    	#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."
        
             # Loop until we get a sam account that is not in the domain
             while ($Username -ne $null) {Write-Host "$SamAccountName is already in AD, please enter Username manually."
    	     $SamAccountName = Read-Host -Prompt "UserName"
    	     $Username = $(try {Get-ADUser $SamAccountName} catch {$null})
    }
        }
    	else
    	{
            #User does not exist then proceed to create the new user account with the following CSV criteria.
             New-ADUser `
                -SamAccountName $Username `
                -UserPrincipalName "$Username@domain.net" `
                -Name "$Firstname, $Lastname" `
                -GivenName $Firstname `
                -Surname $Lastname `
                -Enabled $True `
                -DisplayName "$Lastname, $Firstname" `
                -Path $OldUser `
                -Manager $Manager `
                -Company $company `
                -Mobile $Mobile `
                -OfficePhone $OfficePhone `
                -EmailAddress $email `
                -Title $jobtitle `
                -Department $department `
                -AccountPassword (ConvertTo-SecureString "$Password" -AsPlainText -force) `        
    	}
    }

    CSV Headers:

    -UserToCopy

    -FirstName

    -LastName Sam

    -AccountName

    -DisplayName

    -Department

    -Title -Manager

    -Office

    -Phone

    -Company

    -Password

    -MobilePhone   

    -Email


    • Edited by Jarvis_One Thursday, January 17, 2019 5:00 PM
    Thursday, January 17, 2019 4:58 PM

All replies

  • The csv does not have the field distinguishedName, yet you refer to $user.distinguishedName. Perhaps you want $user.UserToCopy, assuming the value is a DN.

    Richard Mueller - MVP Enterprise Mobility (Identity and Access)

    Thursday, January 17, 2019 5:25 PM
    Moderator
  • Better code design would help.  Also you can have no blank fields in your CSV.

    $ADUsers = Import-csv C:\PScripts\UsersToCreate.csv
    foreach ($User in $ADUsers) {
        
        #Check to see if the user already exists in AD
        if (Get-ADUser -Filter "SamAccountName -eq '$($User.SamAccountName)'") {
            #If user does exist, give a warning
            Write-Warning "A user account with username $Username already exist in Active Directory."
            
            # Loop until we get a sam account that is not in the domain
            while ($Username -ne $null) {
                Write-Host "$SamAccountName is already in AD, please enter Username manually."
                $SamAccountName = Read-Host -Prompt "UserName"
                $Username = $(try { Get-ADUser $SamAccountName } catch { $null })
            }
    } else { #User does not exist then proceed to create the new user account with the following CSV criteria. $oldUser = [ADSI]('LDAP://' + $User.DistinguishedName) $path = $oldUser.Parent -replace 'LDAP://' $usersplat = @{ SamAccountName = $Username UserPrincipalName = "$Username@domain.net" Name = '{0},{1}' -f $User.LastName, $User.FirstName GivenName = $User.FirstName Surname = $User.LastName Enabled = $True DisplayName = '{0},{1}' -f $User.LastName, $User.FirstName Path = $path Manager = $User.Manager Company = $User.Company Mobile = $User.Mobile OfficePhone = $User.Office EmailAddress = $User.Email Title = $User.Title Department = $User.Department AccountPassword = ConvertTo-SecureString $User.Password -AsPlainText -force } New-ADUser @usersplat } }


    \_(ツ)_/








    • Edited by jrv Thursday, January 17, 2019 6:57 PM
    Thursday, January 17, 2019 5:55 PM
  • Nice catch I did change it but still getting the same Syntax errors.

    New-ADUser : The object name has bad syntax
    At E:\PScripts\TESTING-DO NOT USE\CreateUserFromCSV.ps1:47 char:10
    +          New-ADUser `
    +          ~~~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (CN=Peter\, Park....DirectoryEntry:String) [New-ADUser], ADException
        + FullyQualifiedErrorId : ActiveDirectoryServer:8335,Microsoft.ActiveDirectory.Management.Commands.NewADUser
     


    Thursday, January 17, 2019 6:09 PM
  • Using your better code design:

    ConvertToSecureString : The term 'ConvertToSecureString' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
    At line:36 char:34
    +             AccountPassword   = (ConvertToSecureString $User.Password ...
    +                                  ~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : ObjectNotFound: (ConvertToSecureString:String) [], CommandNotFoundException
        + FullyQualifiedErrorId : CommandNotFoundException
     
    New-ADUser : Cannot validate argument on parameter 'Name'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
    At line:39 char:20
    +         New-ADUser @usersplat
    +                    ~~~~~~~~~~
        + CategoryInfo          : InvalidData: (:) [New-ADUser], ParameterBindingValidationException
        + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.NewADUser


    Thursday, January 17, 2019 6:10 PM
  • Just add the missing "-" which got removed by accident.


    \_(ツ)_/

    Thursday, January 17, 2019 6:18 PM
  • This is even simpler and easier to debug:

    function Get-UserOU{
        param ($DistinguishedName)
        $user = [ADSI]"LDAP://$DistinguishedName"
        $user.Parent -replace 'LDAP://'
    }
    
    function Get-NewUserName {
        param ($SamAccountName)
        
        #Check to see if the user already exists in AD
        while (Get-ADUser -Filter "SamAccountName -eq '$SamAccountName'") {
            Write-Host "$($User.SamAccountName) is already in AD, please enter Username manually."
            $SamAccountName = Read-Host -Prompt "UserName"
        }
        $SamAccountName
    }
    
    
    Import-csv C:\PScripts\UsersToCreate.csv |
        ForEach-Object{
            
            $SamAccountName = Get-NewUserName $_.SamAccountNAme
            $usersplat = @{
                SamAccountName    = $SamAccountName
                UserPrincipalName = "$SamAccountName@domain.net"
                Name              = '{0},{1}' -f $_.LastName, $_.FirstName
                GivenName         = $_.FirstName
                Surname           = $_.LastName
                Enabled           = $true
                DisplayName       = '{0},{1}' -f $_.LastName, $_.FirstName
                Path              = Get-UserOU $_.DistinguishedName
                Manager           = $_.Manager
                Company           = $_.Company
                Mobile            = $_.Mobile
                OfficePhone       = $_.Office
                EmailAddress      = $_.Email
                Title             = $_.Title
                Department        = $_.Department
                AccountPassword   = ConvertTo-SecureString $_.Password -AsPlainText -force
            }
            
            New-ADUser @usersplat
        }
    Again... you cannot have blank fields in your CSV.


    \_(ツ)_/




    • Edited by jrv Thursday, January 17, 2019 6:57 PM
    Thursday, January 17, 2019 6:19 PM
  • I don't follow? 

    Wouldn't adding the "-" make the assignment expressions not valid?
    Thursday, January 17, 2019 6:25 PM
  • I don't follow? 

    Wouldn't adding the "-" make the assignment expressions not valid?

    You really need to learn basic PowerShell and this would not be so painful.

    ConvertTo-SecureString

    Please read the error message as it explicitly tells you that this is the problem.


    \_(ツ)_/

    Thursday, January 17, 2019 6:29 PM
  • Oh no I got that the first time you posted your code. I thought you where referencing the assignments.
    Thursday, January 17, 2019 6:43 PM
  • ConvertTo-SecureString : Cannot convert 'System.String' to the type 'System.Management.Automation.SwitchParameter' required by parameter 'Force'. 
    At line:39 char:80
    + ... ountPassword   = ConvertTo-SecureString $_.Password AsPlainText force
    +                                                                     ~~~~~
        + CategoryInfo          : InvalidArgument: (:) [ConvertTo-SecureString], ParameterBindingException
        + FullyQualifiedErrorId : CannotConvertArgument,Microsoft.PowerShell.Commands.ConvertToSecureStringCommand
     
    New-ADUser : Cannot validate argument on parameter 'Name'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
    At line:42 char:20
    +         New-ADUser @usersplat
    +                    ~~~~~~~~~~
        + CategoryInfo          : InvalidData: (:) [New-ADUser], ParameterBindingValidationException
        + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.NewADUser
     

    I added the "-" to force and ASplainText


    But are still getting

    New-ADUser : Cannot validate argument on parameter 'Path'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
    At line:42 char:20
    +         New-ADUser @usersplat
    +                    ~~~~~~~~~~
        + CategoryInfo          : InvalidData: (:) [New-ADUser], ParameterBindingValidationException
        + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.NewADUser

    I changed the "@" to the "$" to make it a variable.

    Which in part runs into:

    New-ADUser : The name provided is not a properly formed account name
    At line:41 char:9
    +         New-ADUser $usersplat
    +         ~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (CN=System.Colle...uilder,DC=local:String) [New-ADUser], ADException
        + FullyQualifiedErrorId : ActiveDirectoryServer:1315,Microsoft.ActiveDirectory.Management.Commands.NewADUser

    • Edited by Jarvis_One Thursday, January 17, 2019 6:54 PM
    Thursday, January 17, 2019 6:46 PM
  • Again.  read the error.  You need to add the dashes which got removed by accident.


    \_(ツ)_/

    Thursday, January 17, 2019 6:57 PM
  • Seems like you're the one not reading man. I added them already the last part was the result of after adding the dashes,

    Thursday, January 17, 2019 6:59 PM
  • I apologize for the errors but my intent was not to write your code but to show you how to structure code so that it is easier to manage.  I amm assuming that you either know PowerShell basics or that you will be looking up the CmdLets and syntaxes as you learn.


    \_(ツ)_/

    Thursday, January 17, 2019 6:59 PM
  • Where did you add the dashes.  I didn't say add arbitrary dashes.  I said add the dashes required by the CmdLet noted in the error.  Please read the whole error carefully.


    \_(ツ)_/

    Thursday, January 17, 2019 7:05 PM
  • Also understand that we cannot run your CSV or access your system.  You have to do some thinking and try to understand how to use code and error messages.

    As noted before, I posted the code to show you how to structure your code.  You still need to debug what you want.  Start by learning how to write code incrementally.  Use the bits inside the loop and replace all CSV variables with actual strings creating one user. This will help you understand how the CmdLet works.

    New coders tend to think that just copying and pasting code without a complete understanding of how it works is good enough.  It is critical to take time to fully understand what each piece of code does. This cannot be learned from asking questions in a forum with any complex piece of code.

    You are clearly making changes without any understanding of the PowerShell syntax or of how the CmdLets work. THis can lead us to going around in circles endlessly.

    Stopping and thinking is the first best step.


    \_(ツ)_/

    Thursday, January 17, 2019 7:13 PM
  • What does tying in another one of my threads do for me? 

    If you are going to help please do otherwise make your departure from my thread and go assist someone else.

    Your absolutely NO HELP whats so ever! You seem to think I am doing this for fun and have the time to be toying round with concepts at the moment.

    Just to be clear I made changes to your erroneous switch calling. 

    Good Day sir.





    • Edited by Jarvis_One Thursday, January 17, 2019 8:29 PM
    Thursday, January 17, 2019 8:05 PM
  • What does tying in another one of my threads do for me? 

    If you are going to help please do otherwise make your departure from my thread and go assist someone else.

    Your absolutely NO HELP whats so ever! You seem to think I am doing this for fun and have the time to be toying round with concepts at the moment.

    Just to be clear I made changes to your erroneous switch calling. 

    Good Day sir.





    I fixed my posted code a long time ago.  Did you even look?

    You have to understand the basics concepts of PowerShell and coding.  We cannot design write and debug code on your system for obvious reasons.

    Take a break.  Come back with a clear head and try to understand what is going on with the code.  You will likely have to learn basic coding and PowerShell as well as basic AD programming.  This is not like old batch files.  You need to gain an understanding of what is happening,.

    Even if ou try to fix your original code all of the basics I have noted are true.  Start with only the minimal code required.  Use only a couple or parameters and build up until you find the issues.

    Pay close attention to error messages.  Learn to run code in the debugger and inspect the variables passed.


    \_(ツ)_/

    Thursday, January 17, 2019 8:53 PM