Powershell ADUser command not syncing with AD - powershell

The text below is my attempt to use the Import-Module ActiveDirectory
Import-Module ActiveDirectory
#Get-Command New-ADUser -Syntax
$firstName = Read-Host -Prompt "Please enter the first name"
$lastName = Read-Host -Prompt "Please enter the last name"
$UserParams = #{
Name = "$firstName $lastName"
GivenName = $firstName
Surname = $lastName
UserPrincipalName = "$firstName.lastname"
EmailAddress = "$firstName.$lastName#<domain>"
ChangePasswordAtLogon = 1
Enabled = 1
StreetAddress = "<info>"
Office = "<info>"
State = "<info>"
PostalCode = "<info>"
Country = "<info>"
Path = "OU=External,OU=Workers,OU=Group,DC=<domain>,DC=com"
}
New-ADUser #UserParams
When this is ran I get this error
+ New-ADUser #UserParams
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (CN=test user,OU...=<domain>,DC=com:String) [New-ADUser], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:<port>,Microsoft.ActiveDirectory.Management.Commands.NewADUser
Is the path incorrect? I know it should be correct because I have copied it from distinguishedName in String Attribute Editor.

Related

Trying to create multiple AD users at once using CSV and Powershell. Splatting appears to be causing issues

As the title says, I'm trying to use powershell in combination with a CSV file to create multiple users at once but keep encountering an error. I have included the error and my code below. Any help in fixing this is much appreciated!
Powershell Error:
New-ADUser : The object name has bad syntax
At line:32 char:17
+ } } New-ADUser #hash
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (CN=Test User...REFORM,DC=local:String) [New-ADUser], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:8335,Microsoft.ActiveDirectory.Management.Commands.NewADUser
Powershell Code:
$ADUsers = Import-csv EnterFilePathHere
foreach ($User in $ADUsers)
{
$Firstname = $User.firstname
$Surname = $User.surname
$Password = $User.password
$OU = $User.ou
$Description = $User.description
$Email = $User.email
$Username = -join("$Firstname", "_", "$Surname")
$hash = #{
SamAccountName = $Username
UserPrincipalName = "$Username#EnterDomainHere"
Name = "$($User.firstName) $($User.surName)"
givenName = $FirstName
surName = $Surname
Enabled = $true
ChangePasswordAtLogon = $false
DisplayName = "$FirstName $Surname"
Path = $OU
Description = $Description
EmailAddress = $Email
AccountPassword = (ConvertTo-SecureString "$Password" -AsPlainText -Force)
} New-ADUser #hash
}
As mentioned by theo, New-ADUser #hash is currently outside of the loop. Frustratingly, when I move it up a line (as I now have in the code displayed above) I am faced with another error:
At line:32 char:15
+ } New-AdUser #hash }
+ ~~~~~~~~~~
Unexpected token 'New-AdUser' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : UnexpectedToken
Here's an example of the CSV file as displayed in Excel. The file is saved as CSV UTF-8 (Comma delimited
You should try to indent better, then you will spot the error soon enough. The New-ADUser cmdlet should be on its own separate line right below the closing bracket of the Hashtable.
Also, you don't need all those variables, just a few to make things easier
$ADUsers = Import-Csv -Path '<EnterFilePathHere>'
foreach ($User in $ADUsers) {
# for convenience create some variables that will be used more often
$Firstname = $User.firstname
$Surname = $User.surname
$Username = '{0}_{1}' -f $Firstname, $Surname
# create the splatting Hashtable
$hash = #{
SamAccountName = $Username
UserPrincipalName = "$Username#EnterDomainHere"
Name = "$Firstname $Surname"
GivenName = $FirstName
Surname = $Surname
DisplayName = "$FirstName $Surname"
Enabled = $true
ChangePasswordAtLogon = $false
Path = $User.ou
Description = $User.description
EmailAddress = $User.email
AccountPassword = (ConvertTo-SecureString $User.password -AsPlainText -Force)
}
New-ADUser #hash
}

Running my poweshell script produces an error and doesn't onboard new users

I am trying to on-board users utilizing Powershell for the company I am working for, however I am coming into an issue that states the directory object is not found. Can anyone assist me with what my error is and how to fix it?
I have tried to remove the city, organizational unit and have tried editing my excel csv file several times, but all tests have failed
# 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:\Users\padmin\Documents\users.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.username
$Password = $User.password
$Firstname = $User.firstname
$Lastname = $User.lastname
$OU = $User.ou #This field refers to the OU the user account is to be created in
$email = $User.email
$streetaddress = $User.streetaddress
#$city = $User.city
$zipcode = $User.zipcode
$state = $User.state
$country = $User.country
$telephone = $User.telephone
$jobtitle = $User.jobtitle
$company = $User.company
$department = $User.department
$Password = $User.Password
#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
#Account will be created in the OU provided by the $OU variable read from the CSV file
New-ADUser `
-SamAccountName $Username `
-UserPrincipalName "$Username#greenkeyllc.com" `
-Name "$Firstname $Lastname" `
-GivenName $Firstname `
-Surname $Lastname `
-Enabled $True `
-DisplayName "$Lastname, $Firstname" `
-Path $OU `
#-City $city `
-Company $company `
-State $state `
-StreetAddress $streetaddress `
-OfficePhone $telephone `
-EmailAddress $email `
-Title $jobtitle `
-Department $department `
-AccountPassword (convertto-securestring $Password -AsPlainText -Force) -ChangePasswordAtLogon $True
}
}
Expected results is to add a user into the proper organizational unit (different office locations) within the local active directory. The actual results are the error below.
New-ADUser : Directory object not found
At C:\Users\padmin\Documents\bulk_users1.ps1:41 char:3
+ New-ADUser `
+ ~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (CN=Bob Jake,CN=...eenkey,DC=local:String) [New-ADUser], ADIdentityNotFoundException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.NewADUser
-Company : The term '-Company' 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 C:\Users\padmin\Documents\bulk_users1.ps1:51 char:13
+ -Company $company `
+ ~~~~~~~~
+ CategoryInfo : ObjectNotFound: (-Company:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
The # commented out line in the middle of the script breaks your expected line continuation:
-Path $OU `
#-City $city `
-Company $company `
Put the arguments in to a hashtable and splat them instead:
$NewADUserArgs = #{
SamAccountName = $Username
UserPrincipalName = "$Username#greenkeyllc.com"
Name = "$Firstname $Lastname"
GivenName = $Firstname
Surname = $Lastname
Enabled = $True
DisplayName = "$Lastname, $Firstname"
Path = $OU
# City = $city
Company = $company
State = $state
StreetAddress = $streetaddress
OfficePhone = $telephone
EmailAddress = $email
Title = $jobtitle
Department = $department
AccountPassword = (convertto-securestring $Password -AsPlainText -Force)
ChangePasswordAtLogon = $true
}
New-ADUser #NewADUserArgs
Now you can easily comment out a single entry in the argument table without worrying about line breaks and all those pesky backticks

AD Account Will Not Create If Duplicate First Name & Second Name

I am creating a script to create users on a domain for one of my clients (NHS in the UK), however it currently refuses to create the AD User & exchange account if the user has a First & Second Name that Already Exists within the AD.
I have already bypassed username duplication by adding a number onto the end of the usernames if they already exist. However, if the first / second name is duplicated it will not create the account.
$DisplayName = $Surname + " " + $GivenName
$Mail = $GivenName + "." + $Surname + "#" + "royalberkshire.nhs.uk"
$MailAlias = $GivenName + "." + $Surname + "#" + $DNSRoot2
$SInitial = $Surname[0]
$Initial = $GivenName[0]
$SAMAccountName = $Surname + "" + $Initial
$SAMAccountLower = $SAMAccountName.ToLower()
$UserPrincipalName = $Surname+$Initial
$HD = "U"
$HDir = "\\RBHFILRED002\"
$AC = "Users_01$\"
$DH = "Users_02$\"
$IM = "Users_03$\"
$NS = "Users_04$\"
$TZ = "Users_05$\"
$Folder = if ($SInitial -in 'a','b','c'){$AC}
elseif ($SInitial -in 'd','e','f', 'g','h'){$DH}
elseif ($SInitial -in 'i','j','k', 'l','m'){$IM}
elseif ($SInitial -in 'n','o','p', 'q','r','s'){$NS}
else {$TZ}
$group1 = "zz Everyone"
$group2 = "Safeboot Domain Users"
$defaultname = $SAMAccountName
$email = $GivenName + "." + $Surname
$i = 1
cls
while ((Get-ADUser -Identity $SAMAccountName -ErrorAction SilentlyContinue) -ne $null) {
$SamAccountName = $defaultname + [string]$i
$Mail = $email + [string]$i + "#" + "royalberkshire.nhs.uk"
$i++
}
$NewUserParams = #{
Path = "OU=Users,OU=RBFT,DC=rbbh-tr,DC=nhs,DC=uk"
SamAccountName = $SAMAccountName
Name = $DisplayName
DisplayName = $DisplayName
GivenName = $GivenName
Surname = $Surname
EmailAddress = $Mail
UserPrincipalName = "$SAMAccountName#rbbh-tr.nhs.uk"
Title = $title
HomeDrive = $HomeDrive
HomeDirectory = "$HDir$Folder$SAMAccountName"
Description = $Description
ChangePasswordAtLogon = $true
PasswordNeverExpires = $false
AccountPassword = $defpassword
Enabled = $true
}
New-ADUser #NewUserParams
Add-ADGroupMember -Identity $group1 -Members $SAMAccountName
Start-Sleep -s 10
Add-ADGroupMember -Identity $group2 -Members $SAMAccountName
cls
echo "Please Wait Whilst We Find The AD Account & Create The Exchange Mailbox.."
Start-Sleep -s 30
Enable-Mailbox -Identity $SAMAccountName
cls
Any Ideas?
EDIT 1 - Error output:
Name : Microsoft.Exchange.Management.PowerShell.E2010
PSVersion : 1.0
Description : Admin Tasks for the Exchange Server
Name : Microsoft.Exchange.Management.Powershell.Support
PSVersion : 1.0
Description : Support Tasks for the Exchange Server
This tool is to be used for creating User Accounts for the RBFT Domain under
Ultima Business Solutions only. If this applies, please hit any key to continue.
Get-ADUser : Cannot find an object with identity: 'TimmsJ1' under: 'DC=rbbh-tr,DC=nhs,DC=uk'. At C:\Users\timmsj\Desktop\Scripts\User_Creation\RBFT_UC_Dev.ps1:140 char:9
+ While ((Get-ADUser -Identity $SAMAccountName -ErrorAction SilentlyCon ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (TimmsJ1:ADUser) [Get-ADUser], ADIdentityNotFoundException
+ FullyQualifiedErrorId : Cannot find an object with identity: 'TimmsJ1' u nder: 'DC=rbbh-tr,DC=nhs,DC=uk'.,Microsoft.ActiveDirectory.Management.Comm ands.GetADUser
New-ADUser : An attempt was made to add an object to the directory with a name that is already in use At C:\Users\timmsj\Desktop\Scripts\User_Creation\RBFT_UC_Dev.ps1:166 char:1
+ New-ADUser #NewUserParams
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (CN=Timms James,...tr,DC=nhs,DC=uk:String) [New-ADUser], ADException
+ FullyQualifiedErrorId : An attempt was made to add an object to the dire ctory with a name that is already in use,Microsoft.ActiveDirectory.Managem ent.Commands.NewADUser
Add-ADGroupMember : Cannot find an object with identity: 'TimmsJ1' under: 'DC=rbbh-tr,DC=nhs,DC=uk'.
At C:\Users\timmsj\Desktop\Scripts\User_Creation\RBFT_UC_Dev.ps1:167 char:1
+ Add-ADGroupMember -Identity $group1 -Members $SAMAccountName
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (TimmsJ1:ADPrincipal) [Add-ADGro upMember], ADIdentityNotFoundException
+ FullyQualifiedErrorId : SetADGroupMember.ValidateMembersParameter,Micros oft.ActiveDirectory.Management.Commands.AddADGroupMember
Add-ADGroupMember : Cannot find an object with identity: 'TimmsJ1' under:
'DC=rbbh-tr,DC=nhs,DC=uk'. At C:\Users\timmsj\Desktop\Scripts\User_Creation\RBFT_UC_Dev.ps1:169 char:1
+ Add-ADGroupMember -Identity $group2 -Members $SAMAccountName
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (TimmsJ1:ADPrincipal) [Add-ADGroupMember], ADIdentityNotFoundException
+ FullyQualifiedErrorId : SetADGroupMember.ValidateMembersParameter,Microsoft.ActiveDirectory.Management.Commands.AddADGroupMember
Please Wait Whilst We Find The AD Account & Create The Exchange Mailbox..
Enable-Mailbox : The operation couldn't be performed because object 'TimmsJ1' couldn't be found on 'rbhdc8red002.rbbh-tr.nhs.uk'.
At C:\Users\timmsj\Desktop\Scripts\User_Creation\RBFT_UC_Dev.ps1:175 char:1
+ Enable-Mailbox -Identity $SAMAccountName
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (0:Int32) [Enable-Mailbox], Manage mentObjectNotFoundException
+ FullyQualifiedErrorId : 637D7B43,Microsoft.Exchange.Management.Recipient Tasks.EnableMailbox
Username:
TimmsJ1
Password:
Welcome123
Email:
James.Timms1#royalberkshire.nhs.uk
Job Title - Department:
Test - Ultima
Home Directory:
\\RBHFILRED002\Users_05$\TimmsJ1
You will need to manually set the new user's group memberships. Please Do This
Before Sending The User's Account Details.
Press Any Key To Close
The parameter -Name sets not only the attribute name but also cn (common name), which must be unique just like sAMAccountName. To fix the issue change this:
$NewUserParams = #{
Path = "OU=Users,OU=RBFT,DC=rbbh-tr,DC=nhs,DC=uk"
SamAccountName = $SAMAccountName
Name = $DisplayName
DisplayName = $DisplayName
...
}
into this:
$NewUserParams = #{
Path = "OU=Users,OU=RBFT,DC=rbbh-tr,DC=nhs,DC=uk"
Name = $SAMAccountName
DisplayName = $DisplayName
...
}
When omitting -SamAccountName the value of the parameter -Name is automatically assinged as the sAMAccountName too.

New-ADUser: The object name has bad syntax

I want to create a new AD user but it is showing error message like:
New-ADUser : The object name has bad syntax
At C:\Users\sa\Desktop\AD User Script.ps1:22 char:1
+ New-ADUser -Name "$displayName" -UserPrincipalName "($initials) ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (CN=fbfb regbgfn...IT,DC=,DC=it:String) [New-ADUser], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:8335,Microsoft.ActiveDirectory.Management.Commands.NewADUser
$firstName = Read-Host "Indtast dit fornavn"
$middlename = Read-Host "Indtast dit mellemnavn (Hvis du ikke har et tryk Enter)"
$surname = Read-Host "Indtast dit efternavn"
$PlainPassword = "Admin100"
$SecurePassword = $PlainPassword | ConvertTo-SecureString -AsPlainText -Force
$group = Read-Host "Hvilken Gruppe? [1 - Help] [2 - Sof] [3 - In]"
$firstletter1 = $firstname.Substring(0, 1)
$secondletter = $firstname.Substring(0, 2)
$firstletter2 = $middlename.Substring(0, 1)
$firstletter3 = $surname.Substring(0, 1)
$displayName = "$firstName $middlename$surname"
if ($middlename -eq $Null) {
$initials = "$firstletter1$secondletter$firstletter3".ToLower()
Write-Host "$initials"
}
else {
$initials = "$firstletter1$firstletter2$firstletter3".ToLower()
Write-Host "$initials"
}
$Searcher = [ADSISearcher]"(sAMAccountName=$initials)"
$Results = $Searcher.FindOne()
If ($Results -eq $Null) {
If ($group -eq 1) {
New-ADUser -Name "$displayName" -UserPrincipalName "($initials)" -Path "OU=,OU=,OU-,OU=,DC=,DC=" -Enabled $true -AccountPassword $SecurePassword -ChangePasswordAtLogon $True -DisplayName "$initials" -GivenName "$firstname" -HomeDrive "P: \\fileshare\Privat\%$initials%" -Initials "$initials" -SamAccountName "$firstletter1" -Surname "$surname"
}
Can you check the UserPrincipalName and sAMAccountName formats. An example would be:
Name: John Smith
UPN: smithj#example.com
sAMAccountName : smithj
UPN Format
A UPN consists of a UPN prefix (the user account name) and a UPN suffix (a DNS domain name). The prefix is joined with the suffix using the "#" symbol. For example, "someone# example.com". A UPN must be unique among all security principal objects within a directory forest. This means the prefix of a UPN can be reused, just not with the same suffix.

Name provided not a properly formed account name

Can someone help with another error I'm experiencing?
My create user script is giving me another error.
foreach ($User in $ADUsers)
{
#Read user data from each field in each row and assign the data to a variable as below
$Username = $User.ID
$Password = $User.BDATE
$Firstname = $User.FNAME
$Lastname = $User.LNAME
$Department = $User.GRD
$Company = $User.SCHID #This field refers to the OU the user account is to be moved to
# Choose OU
switch ($Company)
{
"1480" {$OU = 'OU=students,OU=users,ou=hs,dc=clasd,dc=net'}
"1479" {$OU = 'OU=students,OU=users,ou=elem,dc=clasd,dc=net'}
"1480" {$Folder = '\\hs-ss\students\hs'}
"1479" {$Folder = '\\hs-ss\students\elem'}
}
#Account will be created in the OU provided by the $OU variable read from the CSV file
New-ADUser `
-SamAccountName $Username `
-UserPrincipalName "$Username#clasd.net" `
-Name $Firstname $Lastname `
-GivenName $Firstname `
-Department "$Department" `
-Company "$Company" `
-EmailAddress "$Username#clasd.net" `
-Surname $Lastname `
-Enabled $True `
-Scriptpath "login.vbs" `
-DisplayName "$Firstname $Lastname" `
-Path $OU `
-Homedrive "Z" `
-homedirectory "$Folder\$username" `
-AccountPassword (ConvertTo-SecureString "$User.BDATE" -AsPlainText -Force) `
-ChangePasswordAtLogon $true
}
My error is:
New-ADUser : The name provided is not a properly formed account name
At C:\AD_Scripts\psscripts\user_create.ps1:34 char:9
+ New-ADUser `
+ ~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (CN=\\ ,OU=stude...dc=clasd,dc=net:String) [New-ADUser], ADException
+ FullyQualifiedErrorId : The name provided is not a properly formed account name,Microsoft.ActiveDirectory.Management.Commands.NewADUser
EDIT 1
If I Write-Host $Firstname $Lastname I get "User2 User2" which is correct.
EDIT 2
The account still gets created even with that message I receive.
Edit 3
I've gone ahead and splatted things like I've been told. I'm still struggling with the same error though. Only this time the user does NOT get created.
# Import active directory module for running AD cmdlets
Import-Module activedirectory
#Store the data from ADUsers.csv in the $ADUsers variable
$ADUsers = Import-csv userimport.csv
#Store report in log file in the $log variable
$log = "log.txt"
#Set Additional Variables
$Password = (ConvertTo-SecureString -AsPlainText "$User.BDATE" -Force)
$DisplayName = "$User.FNAME+ ' ' + $user.LNAME"
$Company = $User.SCHID
# Choose OU
Switch ($Company)
{
"1480" {$OU = 'OU=students,OU=users,ou=hs,dc=clasd,dc=net'}
"1479" {$OU = 'OU=students,OU=users,ou=elem,dc=clasd,dc=net'}
"1480" {$Folder = '\\hs-ss\students\hs'}
"1479" {$Folder = '\\hs-ss\students\elem'}
}
Write-Host $DisplayName
#Create Hash Table for New User Creation
$ADUsers = #{
'SamAccountName' = "$User.ID"
'UserPrincipalName' = "$User.ID + '#clasd.net'"
'GivenName' = "$User.FNAME"
'SurName' = "$User.LNAME"
'EmailAddress' = "$User.ID = '#clasd.net'"
'Path' = $OU
'Department' = "$User.GRD"
'Company' = "$User.SCHID"
'AccountPassword' = $Password
'ChangePasswordAtLogon' = $true
'Enabled' = $true
'DisplayName' = "$DisplayName"
'Name' = $Displayname
}
#Call New-ADUser with the parameters Above
Foreach ($User in $ADUsers) {
New-ADUser #ADUsers}
PS C:\AD_Scripts\psscripts> .\Untitled1.ps1
CN=User2 User2,OU=Students,OU=Users,OU=Elem,DC=clasd,DC=net.FNAME+ ' ' + CN=User2 User2,OU=Students,OU=Users,OU=Elem,DC=clasd,DC=net.LNAME
New-ADUser : The name provided is not a properly formed account name
At C:\AD_Scripts\psscripts\Untitled1.ps1:48 char:1
+ New-ADUser #ADUsers}
+ ~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (CN=CN\=User2 Us...dc=clasd,dc=net:String) [New-ADUser], ADException
+ FullyQualifiedErrorId : The name provided is not a properly formed account name,Microsoft.ActiveDirectory.Management.Commands.NewADUser
I've updated powershell to version 4 and I no longer receive any errors in my original script that I posted. Previously I was using Ver 3