PowerShell Script Error Need help figuring out issue please.

Hi All,

I am pretty new to PowerShell and script writing but am learning from videos on Pluralsight courses.

I have been working on some PowerShell script tools and have run into a issue I cannot figure out at this point. I have created a VM lab using VMWare, setup a Domain Controller and a few Test machines in VM to test my scripts and tools.

The tool I am working on at this time is pretty simple script but is throwing an error I cannot figure out. Below is the coding of the script and the error I am getting when I run it with the Computername parameter.

Script Code:

param($Computername, $Location = 'OU=Corporate Computers')

try {
if (Get-AdComputer $Computername) {
Write-Error "The computer name '$Computername' already exist"
return
}
} catch {

}

$DomainDn = (Get-AdDomain).DistinquishedName
$DefaultOuPath = "$Location,$DomainDn"

New-ADComputer -Name $Computername -Path $DefaultOuPath

COMMANDLINE.
.\scriptname.ps1 -$Computername TestVM-03

ERROR I can’t figure out:

New-ADComputer : The object name has bad syntax
At C:\Scriptname.ps1:15 char:1
+ New-ADComputer -Name $Computername -Path $DefaultOuPath
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

+ CategoryInfo :NotSpecified: (CN=-,TestVM-03, :String) [New-AdComputer], ADException
+ FullyQualifiedErroId : ActiveDirectoryServer:8335,Microsoft.ActiveDirectory.Management.Commands.NewADComputer

Remove the dollar sign from your call

.\scriptname.ps1 -Computername TestVM-03

Hi Doug and thanks for the quick reply. I tried what you suggested and got a different error message see below commandline and error received this time.

PS C:\Powershell> .\New-EmployeeOnboardComputer.ps1 -Comutername TestVM-03
New-ADComputer : 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 C:\Powershell\New-EmployeeOnboardComputer.ps1:15 char:22

  • New-ADComputer -Name $Computername -Path $DefaultOuPath
  • CategoryInfo : InvalidData: (:slight_smile: [New-ADComputer], ParameterBindingValidationException
  • FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.Ne
    wADComputer

check the value of $DefaultOuPath
the error you’re showing has part of a OU DN i see

CN=-,TestVM-03,

if i had to guess your path variable is bad

Hi David,

 

The value for the DefaultOuPath is below and seems to be saying my OU=Corporate Computers along with my domain UFEO.COM unless I am missing something.

$DefaultOuPath = “$Location,$DomainDn”

Again this is in a test lab environment and only has 1 domain controller and a few test VM machines.

Could it not be the script at all or and be something not set correctly in the test lab setup? I have looked at this multiple times and seen the exact same script work in the training video just the way I want it to but does not work for me. Any help and direction is appreciated.

just do a write-host $DefaultOuPath on line 14, ensure the value you are passing is a valid DN of an OU
or if in vs code look through the debugging and validate the values in your variables.

look at the error message you are recieving:

  • CategoryInfo :NotSpecified: (CN=-,TestVM-03, :String)

notice the “CN=-,TestVM-03” If that is the value you are actually passing, it is invalid.

Another issue I see is you have a Q instead of a G

$DomainDn = (Get-AdDomain).Distin  q  uishedName

It’s good practice to run each line by itself outside of a script. If you need to simulate a scriptfile just use a function. You can also comment out lines and write things out to yourself for debugging.

function test {
    param($Computername, $Location = 'CN=Computers')
 
    try
    {
        if (Get-AdComputer $Computername)
        {
            Write-Error "The computer name '$Computername' already exist"
            break
        }
    }
    catch
    {
        write-warning $_.exception.message
    }

    $DomainDn = (Get-AdDomain).DistinquishedName
    write-host "DomainDN variable: $Domaindn"

    $DomainDn = (Get-AdDomain).DistinguishedName
    write-host "DomainDN variable again with correct spelling: $Domaindn"

    $DefaultOuPath = "$Location,$DomainDn"
    write-host "Full ou path: $DefaultOuPath"
    #New-ADComputer -Name $Computername -Path $DefaultOuPath
}


test -Computername abc

I’m also not sure return is going to give you the expected result, I’d use break in a function and either break or exit in a scriptfile.

When I attempted the Write-Host this is what I added to line 14 and what I received when I ran the selected line in PS

Line 14 Write-Host $DefaultOuPath = “$Location,$DomainDn”

the return is as follows

PS C:\Powershell> Write-Host $DefaultOuPath = “$Location,$DomainDn”
OU=Corporate Computers, = OU=Corporate Computers,

PS C:\Powershell>

<hr />

If you look at the code of the script line one has the parameters and the location is where I expect the new machine to be placed.

  1. param($Computername,$Location = 'OU=Corporate Computers')

Doug Thanks it worked fine once I corrected the spelling of distinguished. It is always the little things that you overlook time and time again. Again thanks for all the help! I am sure throughout my journey I will run into things that I may need help with and I appreciate having a community like this to come to.

Fantastic! Yeah I wish I would’ve realized just how many helpful people there are in the world years ago. I learned the hard way. Have a wonderful day!

OK, I am back. I have 4 scripts at this point in my toolbelt that does certain things each of them work. These are all account previsioning and maintenance scripts. (Thank you everyone for your insight in getting them working properly), now I am taking my next step by turning them to functions and pulling them all together into an advance function.

Basically I will have a csv file with user account information and a computer for the new employee and create using accounts with certain attributes added to the new AD user accounts and computer objects. At this point when I try to run my Advance function I am getting an error on a line but I am not able to figure out what the error is trying to tell me to be able to fix it.

Below is the script that calls the script with the advance functions and provides the location and name of the input csv file with user info.

C:\Powershell\AdAccountManagementAutomator.ps1

$Employees = Import-Csv -Path C:\Powershell\NewUsersInput.csv
foreach ($Employee in $Employees) {
try {

Create the AD user accounts

$NewUserParams = @{
‘FirstName’ = $Employee.FirstName
‘MiddleInitial’ = $Employee.MiddleInitial
‘LastName’ = $Employee.LastName
‘Title’ = $Employee.Title
}
if ($Employee.Location) {
$NewUserParams.Location = $Employee.Location
}

Grab the username created to use for Set-MyAdUser

$Username = New-EmployeeOnboardUser @NewUserParams

Create the employee’s AD computer account

New-EmployeeOnboardComputer -Computername $Employee.Computername

Set the description for the employee’s computer account

Set-MyAdComputer -Computername $Employee.Computername -Attributes @{‘Description’ = “$($Employee.FirstName) $($Employee.LastName)'s computer” }

Set the dept the employee is in

Set-MyAdUser -Username $Username -Attributes @{‘Department’ = $Employee.Department}

} catch {
Write-Error “$($.Excetion.Message) = Line Number: $($.InvocationInfo.ScriptLineNumber)”
}
}

Below is the error I get when I run this script.

PS C:\powershell> C:\Powershell\CsvImportExample.ps1
C:\Powershell\CsvImportExample.ps1 : = Line Number: 17

  • CategoryInfo : NotSpecified: (:slight_smile: [Write-Error], WriteErrorException
  • FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,CsvImportExample.ps1

C:\Powershell\CsvImportExample.ps1 : = Line Number: 17

  • CategoryInfo : NotSpecified: (:slight_smile: [Write-Error], WriteErrorException
  • FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,CsvImportExample.ps1

C:\Powershell\CsvImportExample.ps1 : = Line Number: 17

  • CategoryInfo : NotSpecified: (:slight_smile: [Write-Error], WriteErrorException
  • FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,CsvImportExample.ps1

C:\Powershell\CsvImportExample.ps1 : = Line Number: 17

  • CategoryInfo : NotSpecified: (:slight_smile: [Write-Error], WriteErrorException
  • FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,CsvImportExample.ps1

C:\Powershell\CsvImportExample.ps1 : = Line Number: 17

  • CategoryInfo : NotSpecified: (:slight_smile: [Write-Error], WriteErrorException
  • FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,CsvImportExample.ps1

C:\Powershell\CsvImportExample.ps1 : = Line Number: 17

  • CategoryInfo : NotSpecified: (:slight_smile: [Write-Error], WriteErrorException
  • FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,CsvImportExample.ps1

C:\Powershell\CsvImportExample.ps1 : = Line Number: 17

  • CategoryInfo : NotSpecified: (:slight_smile: [Write-Error], WriteErrorException
  • FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,CsvImportExample.ps1

C:\Powershell\CsvImportExample.ps1 : = Line Number: 17

  • CategoryInfo : NotSpecified: (:slight_smile: [Write-Error], WriteErrorException
  • FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,CsvImportExample.ps1

Any Ideas on what might be causing these errors? I can tell you also that the csv file has 8 users to be created in it (which looks like the same amount of errors being thrown).

 

The thing is you have all those commands in one try/catch which include a function you do not show. Only you will be able to figure this out in it’s current standing. Things you may want to try

  1. Make multiple try/catch with different errors that indicate more clearly what happened.
  2. Test the functions on their own, not imbedded in another script.
  3. Use [cmdletbinding()] with param block to provide yourself the ability to use verbose.
  4. Along with 3 create verbose output lines you can “turn on” by adding -Verbose paramater (these lines should be informative about what the script is doing at several points throughout the function/script.)

I’d suggest using the free resources available here
for this issue, you should read thebigbookofpowershellhandling:

https://leanpub.com/thebigbookofpowershellerrorhandling

First David Schmidtberger thanks for the info on the ebook I did get it and have read through most of it and it alone has helped me identify more details about the errors I was receiving. I now would like to see if there is something I might be overlooking knowing exactly where the error is coming from and am hoping someone here can help me out.

This is part of my toolset that is currently throwing an error.

[CmdletBinding()]
param (
[string]$FirstName,
[string]$MiddleInitial,
[string]$LastName,
[string]$Location = 'OU=Corporate Users',
[string]$Title
)
process {
$DefaultPassword = 'xxxxxxxxxxxxx'
$DomainDn = (Get-AdDomain).DistinguestedName
$DefaultGroup = 'Default Users Group'

### Figure out what the user name should be
$Username = "$($FirstName.SubString(0,1))$LastName"
$EaPrefBefore = $ErrorActionPreference
$ErrorActionPreference = 'SilentlyContinue'
try {
If (Get-AdUser $Username) {
$Username = "$($FirstName.SubString(0,1))$MiddleInitial$LastName"
If (Get-AdUser $Username) {
Write-Warning "No acceptable username schema could be created"
return
}
}
} catch {

}
### Creat the user account
$ErrorActionPreference = $EaPrefBefore
$NewUserParams = @{
'UserPrincipalName' = $Username
'Name' = $Username
'GivenName' = $FirstName
'Surname' = $LastName
'Title' = $Title
'SamAccountName' = $Username
'AccountPassword' = (ConvertTo-SecureString $DefaultPassword -AsPlainText -Force)
'Enabled' = $true
'Initials' = $MiddleInitial
'Path' = "$Location,$DomainDn"
'ChangePasswordAtLogon' = $true
}

New-AdUser @NewUserParams

### Add the user account to the company standard group
Add-AdGroupMember -Identity $DefaultGroup -Members $Username
$Username
}
}

When I run the tool I get an error and then I check the $Error to get more detail on the error and get the following information…

PS C:\powershell> $Error
C:\Powershell\CsvImportExample.ps1 : = Line Number: 62
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,CsvImportExample.ps1

New-AdUser : The object name has bad syntax
At C:\Powershell\AdAccountManagementAutomator.ps1:62 char:1
+ New-AdUser @NewUserParams
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (CN=JRollins,'OU=Corporate Users',:String) [New-ADUser], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:8335,Microsoft.ActiveDirectory.Management.Commands.NewADUser

Get-AdUser : Cannot find an object with identity: 'JRollins' under: 'DC=UFEO,DC=COM'.
At C:\Powershell\AdAccountManagementAutomator.ps1:36 char:9
+ If (Get-AdUser $Username) {
+ ~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (JRollins:ADUser) [Get-ADUser], ADIdentityNotFoundException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.GetADUser

It talks about New-AdUser : The object name has bad syntax but I have checked spelling and spacing and cannot identify any bad syntax.

I am pulling the info from a CSV file and checked it for extra lines and cannot find anything there either.

Can someone point me in the right direction here or provide some insight I might be overlooking.

I am learning a lot and feel like I am getting pretty close to building my first useful tool in Powershell.

Thanks for any information and help you can provide.

When formatted in an appropriate manner, it’s easy to see you have an errant curly brace. What IDE are you using to write this, because that should’ve pointed out the issue as well. (ISE, VSCode, etc) The curly braces on line 51/52 should be only one curly brace instead.

[CmdletBinding()]
param(
    [string]$FirstName,
    [string]$MiddleInitial,
    [string]$LastName,
    [string]$Location = 'OU=Corporate Users',
    [string]$Title
)

process {
    $DefaultPassword = 'xxxxxxxxxxxxx'
    $DomainDn = (Get-AdDomain).DistinguestedName
    $DefaultGroup = 'Default Users Group'

    ### Figure out what the user name should be
    $Username = "$($FirstName.SubString(0,1))$LastName"
    $EaPrefBefore = $ErrorActionPreference
    $ErrorActionPreference = 'SilentlyContinue'
    try {
        If (Get-AdUser $Username){
            $Username = "$($FirstName.SubString(0,1))$MiddleInitial$LastName"
            If (Get-AdUser $Username) {
                Write-Warning "No acceptable username schema could be created"
                return
            }
        }
    } catch {

    }
        ### Creat the user account
        $ErrorActionPreference = $EaPrefBefore
        $NewUserParams = @{
        'UserPrincipalName' = $Username
        'Name' = $Username
        'GivenName' = $FirstName
        'Surname' = $LastName
        'Title' = $Title
        'SamAccountName' = $Username
        'AccountPassword' = (ConvertTo-SecureString $DefaultPassword -AsPlainText -Force)
        'Enabled' = $true
        'Initials' = $MiddleInitial
        'Path' = "$Location,$DomainDn"
        'ChangePasswordAtLogon' = $true
    }

    New-AdUser @NewUserParams

    ### Add the user account to the company standard group
    Add-AdGroupMember -Identity $DefaultGroup -Members $Username
    $Username
}
}

Hi Doug,

 

Thanks for the feedback I am using PowerShell 5.1 ISE to build my scripts.

Just a couple of things to inquire about.

  1. Do you mean either line 61 or 62 curly bracket should be removed?
  2. Does that also apply if this code is a part of a function?
I would love to be able to tell how many curly brackets should be included in PowerShell code. Is there a tool I could use that would indicate if the special characters are correct in code or a book that explains when and how to use them?

FYI-Update,

After looking and looking for mistakes due to unexpected errors being thrown in the console. I decided to go into AD and check to see if the user accounts and computer object were being created. Come to find out the tool is doing exactly what I wanted with the exception of running without errors.

Here is what I was trying to accomplish and what I was seeing.

I had was creating a Active Directory tool that handled new employee previsioning by

  1. checking to see if the desired username exist or not if not create it.
  2. adding newly created users to the corporate users OU if another group was not specified in the csv file.
  3. add the user account to the specified department in csv.
  4. add the user account's title specified in csv.
  5. create a computer account in AD for the new employee based on csv.
  6. add a description to the computer (i.e. Orlando Thompson's Computer).
So after looking for an account in AD that I was trying to create I was not finding it, I then deleted the information and added new user details and ran the script. It still throw the errors but the actual employee account and computer were created in AD as expected.

Thank everyone for all your input and insight with this, I feel I am on my way to big things in PowerShell (I am sure I will need your help again along the way) ;).

P.S. the error being thrown was that the new employee usernames could not be found (which was to be expected since I was trying to ensure they did not exist first then create them.

Either one, you just have one too many in this example. If you want to make it a function then simply make the function construct and cut and paste the syntactically correct code in between. I personally put it in a function when I was testing it but it appeared to me that you were using it as a script file so I didn’t want to add anything that could cause confusion. I can’t count the amount of times people have put a function in a script file, run it, and then get frustrated that “nothing happened” when in reality it’s simply bringing the function into the session and simply needs to be run after.