New-ADServiceAccount Powershell script is not working

Hi Powershell family,

Hope you are well?
I’m facing one issue in the PowerShell script for the last 4 days. I have created/ modified it more than 50 times same script and tested it. every time it is going to catch or get some error. and error is not clear so can’t find the cause.

can you help me here?
Thanks


if ($action -like 'create_ad_svc_acc') {                      

   

    <#

     | Set-ADAccountPassword -Identity $svcAccountName -Reset -NewPassword (ConvertTo-SecureString $Password -AsPlainText -Force)

    #>

    try{

        $svcAccountName = "testing_account" 

        $passwordExp = "no"

        $InteractiveLogon = "yes"               

        #password

        $password = "Welcome@1234567890"                              

        #organizational unit

        $path = "OU=Service,OU=Accounts,OU=testcompany OU=Administration,DC=domain,DC=internal" #changed the path for company privacy pupose

        #Dormant OU

        $dormantPath = "OU=Users,OU=Dormant,DC=domain,DC=internal"

        #dns host (mandatory)            

        $dnsHost="test.domain.internal" #changed the host for company privacy pupose

        #Set Password expiry

       

type or paste code here

        if ($passwordExp -like 'no'){                  #environment dependent

            $expiryFlag = $True

        }

        else{

            $expiryFlag = $false

        }

                #create new account

                New-ADServiceAccount `

                -SamAccountName $svcAccountName `

                -name $svcAccountName `

                -Enabled $true `

                -Path $path `

                -DNSHostName $dnsHost `

                -AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) `

                sleep 2

                if (Get-ADServiceAccount -Identity $svcAccountName){

                    if ( $InteractiveLogon -like "no"){

                        Add-ADGroupMember -Identity GBL_DenyLogonLocally -Members $svcAccountName

                    }

                }

        Write-Host "Service account has been created"

    }

    catch{

            Write-Warning "There was an error while creating the service account"

    }

    return

}```

What is the error message that you’re getting?

Try putting $_.Exception.Message in your catch block so that you get the message. You can put $ErrorActionPreference = 'STOP' at the top of your script to make sure that all errors are terminating errors and the catch block will be entered.

I would also suggest that you specify the same DC for all cmdlets. Get-ADServiceAccount, might run against a different DC than New-ADServiceAccount before the account has replicated.

1 Like