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

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.

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
}

Powershell ADUser command not syncing with AD

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.

Add ProxyAddresses to separate script

Goal: Append script to add three different SMTP addresses.
Script: https://thesysadminchannel.com/how-to-create-o365-mailboxes-hybrid-exchange/
Code Snippet:
Write-Host "Continuing will create the AD account and O365 Email." -ForegroundColor:Green
Write-Host
$Proceed = $null
$Proceed = Read-Host "Continue? (y/n)"
if ($Proceed -ieq 'y') {
Write-Host "Creating the O365 mailbox and AD Account."
New-RemoteMailbox -Name $fullname -FirstName $firstname -LastName $lastname -DisplayName
$fullname -SamAccountName $logonname -UserPrincipalName $logonname#$domain -PrimarySmtpAddress
$logonname#$domain -Password $password -OnPremisesOrganizationalUnit $OU -DomainController $Server
Write-Host "Done..."
Write-Host
Write-Host
Sleep 5
Write-Host "Adding Properties to the new user account."
Get-ADUser $logonname -Server $Server | Set-ADUser -Server $Server -Description $Description -
Office $Office -StreetAddress $StreetAddress -City $City -State $State -PostalCode $PostalCode -
Country $Country -Title $Title -Department $Department -Company $Company -Manager $Manager -
EmployeeID
$EmployeeID
Write-Host "Done..."
Write-Host
Write-Host
if ($MemberOf) {
Write-Host "Adding Membership Groups to the new user account."
Get-ADUser $logonname -Server $Server | Add-ADPrincipalGroupMembership -Server $Server -
MemberOf $MemberOf
Write-Host "Done..."
Write-Host
Write-Host
}
}
Get-PSSession | Remove-PSSession
What I'm trying to add are these three values:
SMTP:user#domain.com
smtp:user#domain.mail.onmicrosoft.com
smtp:user#domain.onmicrosoft.com
This is along the lines of what I've come up with:
Write-Host "Adding Properties to the new user account."
Get-ADUser $logonname -Server $Server | Set-ADUser -Server $Server -Description $Description
-Office $Office -StreetAddress $StreetAddress -City $City -State $State -PostalCode $PostalCode -
Country $Country -Title $Title -Department $Department -Company $Company -Manager $Manager -
EmployeeID $EmployeeID
Write-Host "Done..."
Write-Host
Write-Host
Write-Host “Setting up TCS E-mail Standard”
$userinfo.ProxyAddresses = "SMTP:" + ($FirstInitial.Add(1)) + ($userinfo.sn) +
"#DOMAIN.COM"
#$userinfo.ProxyAddresses += "smtp:" + ($userinfo.givenname) + "." + ($userinfo.sn) +
"#domain.mail.onmicrosoft.com"
$userinfo.ProxyAddresses += "smtp:" + ($FirstInitial.Remove(1)) + ($userinfo.sn) +
"#domain.onmicrosoft.com"
$userinfo.targetAddress = "SMTP:" + ($userinfo.sAMAccountName) +
"#domain.mail.onmicrosoft.com"
Write-Host "Done..."
Write-Host
Then I get this error:
You cannot call a method on a null-valued expression.
At C:\Users\Temp\CreateStudentEmail.ps1:233 char:21
+ ... $userinfo.ProxyAddresses = "SMTP:" + ($FirstInitial.Add(1 ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At C:\Users\Temp\CreateStudentEmail.ps1:235 char:21
+ ... $userinfo.ProxyAddresses += "smtp:" + ($FirstInitial.Rem ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
The property 'targetAddress' cannot be found on this object. Verify that the property exists and can
be set.
At C:\Users\Temp\CreateStudentEmail.ps1:236 char:21
+ ... $userinfo.targetAddress = "SMTP:" + ($userinfo.sAMAccou ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
Just trying to find a way to incorporate the proxy address section so that I don't have to worry about extra steps.
I pulled the code from another PowerShell I used years ago, then tweaked it a bit, but it DOES actually input SMTP address fields into the AD character. It still throws errors though.
Here is what you need to do:
set-Aduser $samaccountname -Add #{ proxyAddresses = "SMTP:user#domain.com","smtp:user#domain.mail.onmicrosoft.com","smtp:user#domain.onmicrosoft.com" }

student multi add user script, broken filter on get-aduser

hi just student trying to Bulk add Users from a .csv
when using this, its breaking at the User Filter, but I'm unsure why
error says this line is the issue
" if (Get-ADUser -F { sAMAccountName -eq $username })
Get-ADUser: The search filter cannot be recognized"
i think the csv import is fine but I'm new to this so not really sure what causing the filter to break
$ADUsers = Import-csv 'Path'
#$apiRequest = Get-Content -Raw -Path path.json | ConvertFrom-Json
foreach ($User in $ADUsers) {
$firstName = $user.FirstName
$surname = $user.Surname
$branch = $user.Branch
$city = $user.City
$country = $user.Country
$company = $user.CompanyName
$countryCode = $user.CountryCode
$email = $user.Email
$userType = $User.UserType
$vaildUsernameFormat = "[^a-zA-Z_]" # anything that's _not_ a-z or underscore
$username = ($firstName.$surname) -replace $vaildUsernameFormat, '' #removes anything that isn't a-z
$ou = $User.ou
#Check if the user account already exists in AD
if (Get-ADUser -F { sAMAccountName -eq $username }) {
#If user does exist, output a warning message
Write-Warning "A user account $username has already exist in Active Directory."
}
else {
#If a user does not exist then create a new user account
New-ADUser `
-co $country
-company $company
-countryCode $countryCode
-department $department
-displayName $username
-sn $surname
-st $streetName
-title $title
}
}
thanks for anything you can offer
full error message is
Get-ADUser : The search filter cannot be recognized
At "path" csv.ps1:41 char:13
+ if (Get-ADUser -F { sAMAccountName -eq $username }) {
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-ADUser], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:8254,Microsoft.ActiveDirectory.Management.Commands.GetADUser

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.