Check for duplicate - ADUsers in bulk - powershell

I am trying to make a PowerShell script to add users in bulk through a csv file. If the username already exists I want to add the number 1 to the username. How can I do this? I thought I could maybe make an if?
foreach ($User in $ADUsers) {
# Selvlagde variabler for opprettelse av brukere
$Password = Get-RandomCharacters -length 20 -characters 'ABCDEFGHKLMNOPRSTUVWXYZabcdefghiklmnoprstuvwxyz1234567890!._?/-'
$Username = $User.GivenName.substring(0,3) + $User.SurName.substring(0,3)
$Username = $Username.Replace('æ','ae')
$Username = $Username.Replace('ø','o')
$Username = $Username.Replace('å','aa')
$Username = $Username.ToLower()
$Username = $Username.Trim()
$Email = $Username + '#ONPremiumIT.com'
$DisplayName = $User.GivenName + ' ' + $User.SurName
if (condition) {
}
# Bruker splatting for å lagre info om brukere
$userParams = #{
Path = $User.Path
SamAccountName = $Username
UserPrincipalName = $Email
Name = "$($User.GivenName) $($User.SurName)"
GivenName = $User.GivenName
Surname = $User.SurName
Enabled = $true
ChangePasswordAtLogon = $false
DisplayName = $Displayname
Department = $Department
AccountPassword = (ConvertTo-SecureString $Password -AsPlainText -Force)
}
New-ADUser #userParams

You can do that by testing if a user with that SamAccountName already exists. Something like this:
foreach ($User in $ADUsers) {
# Selvlagde variabler for opprettelse av brukere
$Password = Get-RandomCharacters -length 20 -characters 'ABCDEFGHKLMNOPRSTUVWXYZabcdefghiklmnoprstuvwxyz1234567890!._?/-'
$Username = $User.GivenName.substring(0,3) + $User.SurName.substring(0,3)
$Username = $Username.Replace('æ','ae')
$Username = $Username.Replace('ø','o')
$Username = $Username.Replace('å','aa')
$Username = $Username.ToLower()
$Username = $Username.Trim()
# test if a user with that SamAccountName already exists, add an index number if needed
$n = 1 # start index at 1
$newName = $Username # copy to a new variable
while ($true) { # start an endless loop
$usr = Get-ADUser -Filter "SamAccountName -eq '$newName'" -ErrorAction SilentlyContinue
if (!$usr) {
$Username = $newName # assign the $Username variable the unique value
break # exit the loop if the $username is unique in the domain
}
# construct a new username by adding the index to it
$newName = '{0}{1}' -f $Username, $n++
}
$Email = $Username + '#ONPremiumIT.com'
$DisplayName = $User.GivenName + ' ' + $User.SurName
# Bruker splatting for å lagre info om brukere
$userParams = #{
Path = $User.Path
SamAccountName = $Username
UserPrincipalName = $Email
Name = "$($User.GivenName) $($User.SurName)"
GivenName = $User.GivenName
Surname = $User.SurName
Enabled = $true
ChangePasswordAtLogon = $false
DisplayName = $Displayname
Department = $Department
AccountPassword = (ConvertTo-SecureString $Password -AsPlainText -Force)
}
New-ADUser #userParams
}
P.S. The test for the username must come before doing more things with the $Username variable, like using it for the $Email variable. Otherwise, you could have duplicates in that too..

Related

How can I concatenate first and last name in powershell

FirstName,LastName,passcode,Title,Manager_Email
zack,Ased,breast<achievement?&childhood059,manager,zasdasdh#gmail.com
How can I make the Name zack Ased and the username zack.Ased , here is the code I tried
Import-Module ActiveDirectory
$ADUsers = Import-Csv C:\users.csv
foreach ($User in $ADUsers) {
$FirstName = $User.FirstName
$LastName = $User.LastName
$Name = $FirstName + " " + $LastName
$username = $FirstName.$LastName
$password = $User.passcode
$Title = $User.Title
$Manager_Email = $User.Manager_Email
New-ADUser -Name $Name -SamAccountName $username -AccountPassword (ConvertTo-secureString $password -AsPlainText -Force) -Title $Title -ChangePasswordAtLogon $true
Enable-AdAccount -Identity $username
}
using -join:
$FirstName = 'John'
$LastName = 'Smith'
$Name = $FirstName, $LastName -join " "
#the " " is the delimiter, you can input whatever you like, for example a dot:
$Name = $FirstName, $LastName -join "."
see more examples on https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_join
Another method is by putting it in a new string:
$Name = "$($FirstName).$($LastName)"
There are several other possible methods of doing this.

Add users in bulk with csv file

I am trying to make a script that creates users in bulk from a csv file. I tested the script with 5 users, but get the error message "New-ADUser: A value for the attribute was not in the acceptable range of values." I have been searching everywhere, but can't find the mistake!
function Get-RandomCharacters($length, $characters) {
$random = 1..$length | ForEach-Object { Get-Random -Maximum $characters.length }
$private:ofs=""
return [String]$characters[$random]
}
$ADUsers = Import-csv C:\Users\Admin\Users.csv -Delimiter ";"
foreach ($User in $ADUsers)
{
$Password = Get-RandomCharacters -length 20 -characters 'ABCDEFGHKLMNOPRSTUVWXYZabcdefghiklmnoprstuvwxyz1234567890!._?/'
$Username = $User.GivenName.substring(0,3) + $User.SurName.substring(0,3)
$Username = $Username.Replace('æ','ae')
$Username = $Username.Replace('ø','o')
$Username = $Username.Replace('å','aa')
$Username = $Username.ToLower()
$Username = $Username.Trim()
$Email = $Username + '#ONPremiumIT.com'
$DisplayName = $User.GivenName + ' ' + $User.SurName
New-ADUser `
-Path $User.Path `
-SamAccountName $Username `
-UserPrincipalName $Email `
-Name "$User.GivenName $User.SurName" `
-GivenName $User.GivenName `
-Surname $User.SurName `
-Enabled $True `
-ChangePasswordAtLogon $false `
-DisplayName "$Displayname" `
-Department $Department `
-AccountPassword (convertto-securestring $Password -AsPlainText -Force)
}
csv file:
GivenName;SurName;Department;Path
Tobias;Santelmann;it-drift;OU=it-drift,OU=onprit-brukere,DC=sec,DC=core
Maria;Aas;dev-team;OU=dev-team,OU=onprit-brukere,DC=sec,DC=core
Anniken;Arildset;renhold;OU=renhold,OU=onprit-brukere,DC=sec,DC=core
Thea;Urne;regnskap;OU=regnskap,OU=onprit-brukere,DC=sec,DC=core
Marthea;Wichstad;hr;OU=hr,OU=onprit-brukere,DC=sec,DC=core
The error comes from -Name "$User.GivenName $User.SurName", which should have been -Name "$($User.GivenName) $($User.SurName)".
Example:
"$User.GivenName $User.SurName" # --> #{GivenName=Tobias; Surname=Santelmann}.GivenName #{GivenName=Tobias; Surname=Santelmann}.SurName
but when using the Subexpression operator $(..), it does what you want:
"$($User.GivenName) $($User.SurName)" # --> Tobias Santelmann
Also, when using lots of parameters, you can have difficult to spot errors when using those backticks.
I'd suggest using Splatting for that:
$userParams = #{
Path = $User.Path
SamAccountName = $Username
UserPrincipalName = $Email
Name = '{0} {1}' -f $User.GivenName, $User.SurName # or: "$($User.GivenName) $($User.SurName)"
GivenName = $User.GivenName
Surname = $User.SurName
Enabled = $true
ChangePasswordAtLogon = $false
DisplayName = $Displayname
Department = $Department
AccountPassword = (ConvertTo-SecureString $Password -AsPlainText -Force)
}
New-ADUser #userParams

ADuser not adding samAccountName after changing Variable

Thanks in advance !
I have made a script and in this script, I add users from excel to AD and it works for 99% but I need to make 1 change to it but when I do that it gives me errors.
Import-Csv -Path C:\Users\admin.kln\Documents\Project\BOSAN_USERS.csv |foreach{
#All strings of variables you need out of excel
$Firstname = $_.Firstname
$Lastname = $_."Last Name"
$Displayname = $_."Display Name"
$Extraname = $_."Display Name"
$Logonname = $_."Logon Name"
$Accountpassword = $_.AccountPassword
$Description = $_.Description
$Jobtitle = $_."Job Title"
$Department = $_.Department
$Company = $_.Company
$Telephonenumber = $_.TelephoneNumber
$Mobilenumber = $_."Mobile number"
$Street = $_.Street
$PObox = $_."P.O. Box"
$City = $_.City
$State = $_."State / Province"
$Zip = $_.Zip
$Country = $_.Country
$Manager = $_.Manager
$ProxyEmail = $_."Proxy Address + Email(SMTP)"
$ProxyAdress = $_."Proxy Addresss(smpt)"
$ProxySip = $_."Proxy address (SIP)"
$Final = (($_.Firstname.ToLower().Substring(0,1)) + '.' + ($_."Last name".ToLower()))
#int
$i = 1
$u = 1
$o = 1
#Check if its over 18 chars if it is it will be shortened
if ($Displayname.Length -gt 18) { $Displayname = $Displayname.Substring(0,18) }
if ($Extraname.Length -gt 18) { $Extraname = $Extraname.Substring(0,18) }
try
{
while (Get-ADUser -F {SamAccountName -eq $Extraname})
{
Write-Warning "Er bestaat al een account met de naam $Extraname"
$Extraname = $Displayname + [string]$i
$i++
$Logonname = $Logonname + [string]$o
$o++
$Final = (($_.Firstname.ToLower().Substring(0,1)) + '.' + ($_."Last Name".ToLower()))
$Final = $Final + [string]$u
$u++
}
}
catch{}
finally
{
$Logonname = $Logonname -replace ' ',''
$Final = $Final -replace ' ',''
echo $Final
New-ADUser -Path "ou=Users,ou=NLHKH,dc=CONTOSO,dc=com" `
-SamAccountName $Extraname `
-GivenName $Firstname `
-Name $Extraname `
-Surname $Lastname `
-DisplayName $Extraname `
-UserPrincipalName $Final `
-accountpassword(ConvertTo-SecureString "Password1" -AsPlainText -force) `
-ChangePasswordAtLogon $true `
-Description $Description `
-Title $Jobtitle `
-Department $Department `
-Company $Company `
-MobilePhone $Mobilenumber `
-StreetAddress $Street `
-City $City `
-State $State `
-PostalCode $Zip `
-POBOX $PObox
}
}
As you can see it should work like this but I need to change -SamAccountName to $final or at least to the same Variable as $Final. But that won't do.
Personally, I would change quite a lot of your script.
First of all, you need two loops to figure out if
you get a valid unique SamAccountName
you get a valid unique UserPrincipalName
The ProxyAddresses need extra care aswell. You need to create an array of the 3 Proxy* fields in the CSV and add that with parameter OtherAttributes.
Mind that his will not accept a 'normal' array and that it needs to be cast with [string[]] to form a strongly typed string array.
Finally, use Splatting for the New-ADUser cmdlet to get rid of those nasty backticks.
Something like this:
Import-Csv -Path 'C:\Users\admin.kln\Documents\Project\BOSAN_USERS.csv' | ForEach-Object {
# unused fields in the CSV:
# $Logonname = $_."Logon Name"
# $Country = $_.Country
# $Manager = $_.Manager
# construct a SamAccountName from the DisplayName in the CSV
# replace all invalid characters and cut off anything over 20 characters
$SamAccountName = $_."Display Name" -replace '[\x00-\x20"[\]:;|=+*?<>/,#\s]'
if ($SamAccountName.Length -gt 20) { $SamAccountName = $SamAccountName.Substring(0, 20) }
$temp = $SamAccountName
# enter an endless loop to test if that user with that SamAccountName already exists
$i = 1
while ($true) {
$user = Get-ADUser -Filter "SamAccountName -eq '$SamAccountName'" -ErrorAction SilentlyContinue
# if a user with that SamAccountName does not yet exist, we can break out of the loop
if (!$user) { break }
# create a new SamAccountName to test
while (($temp + $i).Length -gt 20) {
$temp = $temp.Substring(0, $temp.Length - 1)
}
$SamAccountName = '{0}{1}' -f $temp, $i
$i++
}
# since your UPN uses a different format than 'SamAccountName#CONTOSO.com',
# start another loop to make sure that too is unique
# CHANGE #CONTOSO.com TO THE REAL DOMAIN NAME
$UserPrincipalName = '{0}.{1}#CONTOSO.com' -f $_.Firstname.Substring(0,1).ToLower(), $_."Last name".ToLower()
$i = 1
while ($true) {
$user = Get-ADUser -Filter "UserPrincipalName -eq '$UserPrincipalName'" -ErrorAction SilentlyContinue
# if a user with that UserPrincipalName does not yet exist, we can break out of the loop
if (!$user) { break }
# create a new UserPrincipalName by adding a sequence number to test
$UserPrincipalName = '{0}.{1}{2}#CONTOSO.com' -f $_.Firstname.Substring(0,1).ToLower(), $_."Last name".ToLower(), $i
$i++
}
# next, create an array of the Proxy Addresses. Watch the spelling in the CSV headers!
$ProxyAddresses = ('SMTP:{0}' -f ($_."Proxy Address + Email(SMTP)" -replace '^SMTP:')),
('smtp:{0}' -f ($_."Proxy Address(smpt)" -replace '^smtp:')),
('SIP:{0}' -f ($_."Proxy address (SIP)" -replace '^SIP:'))
# now that we have unique names and a ProxyAddresses array, we can create the user
$NewUserParms = #{
'SamAccountName' = $SamAccountName
'Name' = ('{0} {1}' -f $_.FirstName, $_."Last Name").Trim()
'DisplayName' = $_."Display Name"
'UserPrincipalName' = $UserPrincipalName
'GivenName' = $_.FirstName
'Surname' = $_."Last Name"
'Description' = $_.Description
'Title' = $_."Job Title"
'Department' = $_.Department
'Company' = $_.Company
'AccountPassword' = ConvertTo-SecureString $_.AccountPassword -AsPlainText -Force
'ChangePasswordAtLogon' = $true
'Enabled' = $true
'OfficePhone' = $_.TelephoneNumber
'MobilePhone' = $_."Mobile number"
'StreetAddress' = $_.Street
'City' = $_.City
'State' = $_."State / Province"
'PostalCode' = $_.Zip
'POBox' = $_."P.O. Box"
'EmailAddress' = $_."Proxy Address + Email(SMTP)" -replace '^SMTP:'
'Path' = "OU=Users,OU=NLHKH,DC=CONTOSO,DC=com"
# ProxyAddresses needs cast to [string[]]
'OtherAttributes' = #{'proxyAddresses' = [string[]]$ProxyAddresses}
# add other properties to set from the CSV here if needed.
# make sure you get the parameter data types correct and always check here:
# https://learn.microsoft.com/en-us/powershell/module/addsadministration/new-aduser?view=win10-ps#parameters
# switch parameters for the cmdlet can also be entered with a value $false or $true
}
try {
# '-ErrorAction Stop' ensures that also non-terminating errors get handled in the catch block
New-ADUser #NewUserParms -ErrorAction Stop
}
catch {
# something bad happened. Change 'Write-Warning' into 'throw' if you want your script to exit here
# inside a catch block, the '$_' automatic variable represents the actual exception object.
Write-Warning "Could not create account $username. $($_.Exception.Message)"
}
}

New-ADUser OtherAttributes var from CSV

I'm using the powershell script below to create new AD accounts from a CSV file. I recently added the vars for $extensionAttribute1 and $extensionAttribute2. I also added the following -OtherAttributes = #{'extensionAttribute1' = $extensionAttribute1;'extensionAttribute2'= $extensionAttribute2}
How can I correct for the following error?
New-ADUser : Cannot validate argument on parameter 'OtherAttributes'. The argument is null or an element of the argument collection contains a null value. At D:\OneDrive\Element Care\Powershell\SACRequest - Create Accounts via CSV.ps1:62 char:30 + ... -OtherAttributes #{'extensionAttribute1' = $extensionAttribute1}
ps script is as follows:
# Import active directory module for running AD cmdlets
Import-Module activedirectory
#Store the data from ADUsers.csv in the $ADUsers variable
$ADUsers = Import-csv "\\server\path\file.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.'First Name:'
$Lastname = $User.'Last Name:'
$OU = 'OU=CONTRACTORS,OU=ACCOUNTS,OU=organization,DC=domain,DC=lan'
$Descritpion = $User.'Account Type'
$company = $User.'Employer:'
$extensionAttribute1 = $User."Submitter Name" # The employee who originally submitted the request.
$extensionAttribute2 = $User."Submitter email" # The email for who originally submitted the request.
# $email = $User.email
# $streetaddress = $User.streetaddress
# $city = $User.city
# $zipcode = $User.zipcode
# $state = $User.state
# $country = $User.country
# $telephone = $User.telephone
# $jobtitle = $User.jobtitle
# $department = $User.department
#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#domain.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 `
-Description $Descritpion `
-AccountPassword (convertto-securestring $Password -AsPlainText -Force) -ChangePasswordAtLogon $True `
-OtherAttributes #{'extensionAttribute1' = $extensionAttribute1;'extensionAttribute2'= $extensionAttribute2}
}
}
The error you recieved came IMO from the typo's you have made in the original code. Apart from that, I would advice you to use Splatting for cmdlets like New-ADUser that can have a lot of parameters. That way you keep the code both readable and maintainable, and you don't need to use the easily overlooked backtick character for line continuation.
Provided your CSV contains all of the values and all column headers are as shown in your code, something like this should work:
# Import active directory module for running AD cmdlets
Import-Module ActiveDirectory
#Store the data from ADUsers.csv in the $ADUsers variable
Import-csv "\\server\path\file.csv" | ForEach-Object {
#Check to see if the user already exists in AD
if ((Get-ADUser -Filter "SamAccountName -eq '$($_.username)'" -ErrorAction SilentlyContinue)) {
#If user does exist, give a warning
Write-Warning "A user account with username $($_.username) already exist in Active Directory."
continue
}
# only store these in variables as they are used in multiple properties
$firstName = $_.'First Name:'
$lastName = $_.'Last Name:'
# create a Hashtable with all properties you want to set for the new user
$properties = #{
'SamAccountName' = $_.username
'UserPrincipalName' = '{0}#domain.com' -f $_.username
'Name' = '{0} {1}' -f $firstName, $lastName
'GivenName' = $firstName
'Surname' = $lastName
'Enabled' = $true
'DisplayName' = '{0}, {1}' -f $lastName, $firstName
'Path' = 'OU=CONTRACTORS,OU=ACCOUNTS,OU=organization,DC=domain,DC=lan'
'City' = $_.city
'Company' = $_.'Employer:'
'State' = $_.state
'StreetAddress' = $_.streetaddress
'OfficePhone' = $_.telephone
'EmailAddress' = $_.email
'Title' = $_.jobtitle
'Department' = $_.department
'Description' = $_.'Account Type'
'AccountPassword' = (ConvertTo-SecureString $_.password -AsPlainText -Force)
'ChangePasswordAtLogon' = $true
'OtherAttributes' = #{'extensionAttribute1' = $_.'Submitter Name';'extensionAttribute2'= $_.'Submitter email'}
# you can comment out any properties you do not need or are missing in the CSV
# 'PostalCode' = $_.zipcode
# 'Country' = $_.country
}
# create the new user using the properties Hashtable (splat)
Write-Host "Creating user $($_.username)"
New-ADUser #properties
}

Add Multiple Users To AD, CSV

I'm attempting to import users via a CSV folder.
I have certain parameters that need to be kept, so I'm only using certain fields.
Powershell
$csv = Import-Csv -Path "newusers.csv"
foreach ($User in $csv)
{
#region Data Generation
$DisplayName = $User.'Surname' + " " + $User.'GivenName'
$Mail = $User.'GivenName' + "." + $User.'Surname' + "#" + "royalberkshire.nhs.uk"
$MailAlias = $User.'GivenName' + "." + $User.'Surname' + "#" + $DNSRoot2
$SInitial = $User.'Surname'[0]
$Initial = $User.'GivenName'[0]
$SAMAccountName = $User.'Surname' + "" + $Initial
$SAMAccountLower = $SAMAccountName.ToLower()
$UserPrincipalName = $User.'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 = $User.'GivenName' + "." + $User.'Surname'
$i = 1
cls
# Create The User
While ((Get-ADUser -Filter "SamAccountName -eq '$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 = $SAMAccountName
DisplayName = $DisplayName
GivenName = $User.'GivenName'
Surname = $User.'Surname'
EmailAddress = $Mail
UserPrincipalName = "$SAMAccountName#rbbh-tr.nhs.uk"
Title = $title
HomeDrive = $HomeDrive
HomeDirectory = "$HDir$Folder$SAMAccountName"
Description = $User.'Description'
ChangePasswordAtLogon = $true
PasswordNeverExpires = $false
AccountPassword = $password
Enabled = $true
}
New-ADUser #NewUserParams -ErrorAction SilentlyContinue
Add-ADGroupMember -Identity $group1 -Members $SAMAccountName
Start-Sleep -s 10
Add-ADGroupMember -Identity $group2 -Members $SAMAccountName
cls
echo "Please Wait Whilst We Create The AD Account & Create The Exchange Mailbox.."
Start-Sleep -s 30
Enable-Mailbox -Identity $SAMAccountName
cls
echo "Please Wait Whilst We Activate The Exchange Mailbox..."
Start-Sleep -s 15
# Sets The User Up With The Randomised Password, And Re-Encrypts It For Double Protection
Set-ADAccountPassword -Identity $SAMAccountName -Reset -NewPassword (ConvertTo-SecureString -AsPlainText $random -Force)
cls
}
CSV
User GivenName Surname Description
User James Timms Test
User James Timms Test
User Hulk Hogan Test
User Ultimate Warrior Test
User The Rock Test
User Dwayne Johnson Test
The script does not run. It tells me that the Search Filter Cannot Be Recognized.
It just errors on me.
It works with a single user fine using Write-Hosts and Inputs.
However with the CSV it doesn't work.
I must note, this is also the first time I've created users via a CSV on powershell.
Does anybody have any idea on how to fix this issue?
I got it working,
Turns out when I was building the CSV within Excel 2016 it wasn't adding the commas to seperate values.
I ended up opening the CSV within notepad and added commas to separate the values.
Powershell reads the Values based on Comma Seperation, so if there are no commas, it doesn't know what values to push out.