#Enter a path to your import CSV file
$ADUsers = Import-csv C:\scripts\newusers.csv
foreach ($User in $ADUsers)
{
$Username = $User.username
$Password = $User.password
$Firstname = $User.firstname
$Lastname = $User.lastname
$Department = $User.department
$OU = $User.ou
#Check if the user account already exists in AD
if (Get-ADUser -F {SamAccountName -eq $Username}) -SearchBase "DC=XXX,DC=NET"
{
#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
#Account will be created in the OU listed in the $OU variable in the CSV file; don't forget to change the domain name in the"-UserPrincipalName" variable
New-ADUser `
-SamAccountName $Username `
-UserPrincipalName "$Username@yourdomain.com" `
-Name "$Firstname $Lastname" `
-GivenName $Firstname `
-Surname $Lastname `
-Enabled $True `
-ChangePasswordAtLogon $True `
-DisplayName "$Lastname, $Firstname" `
-Department $Department `
-Path $OU `
-AccountPassword (convertto-securestring $Password -AsPlainText -Force)
}
}
-SearchBase “DC=XXX,DC=NET” should be inside the ().
if(Get-ADUser -F {SamAccountName -eq $Username} -SearchBase "DC=XXX,DC=NET"){
}
Thanks so much for your quick reply. Unfortunately, I’m now getting the following error:
Get-ADUser : Error parsing query: ‘SamAccountName -eq $Username’
Error Message: 'Operator Not supported: ’ at position: '16
Thanks!
Check your query string and ensure that -eq is written with a hyphen and not some other dash character that just looks really similar. There are a few of those.
Sir, thanks for much for your help, that seemed to resolve some other issues I was having. I am now getting the following error:
New-ADUser: A paramater cannot be found that matches paramenter name ‘Gecos’
-Gecos <<<< $gecos `
I believe gecos is a valid parameter for New-ADUser so I don’t understand what problem is with this line…
gecos…what’s that !.
Please read the documentation for New-AdUser to see the parameters and examples.
Get-Help New-AdUser -Online
Sorry, I was looking at a different script using OtherAtrributes…thanks! How do I give you both credit?