I am pretty new to powershell and have a code that I found. I had it working but now it is no longer working. I didn't change anything with the variable so I am not sure what is going on. Here is a link to a Screenshot of the code and error. Please let me know if you need any other information
https://imgur.com/a/ntEhdoV
Thank you!
Import-Module activedirectory
$ADUsers = Import-csv 'C:\Users\Desktop\Powershell files\EM-mis-new-AD.csv'
foreach ($User in $ADUsers)
{
$Username = $User.username
$Password = $User.password
$Firstname = $User.firstname
$Lastname = $User.lastname
$OU = $User.ou
$Password = $User.Password
if (Get-ADUser -F {SamAccountName -eq $Username})
{
Write-Warning "A user account with username $Username already exist in Active Directory."
}
else
{
New-ADUser `
-SamAccountName $Username `
-UserPrincipalName "$Username#Mydomain" `
-Name "$Firstname $Lastname" `
-GivenName $Firstname `
-Surname $Lastname `
-Enabled $True `
-DisplayName "$Firstname, $Lastname" `
-Path $OU `
-AccountPassword (convertto-securestring $Password -AsPlainText -Force) -ChangePasswordAtLogon $True
}
}
Error:
Get-ADUser : Variable: 'Username' found in expression: $Username is not defined.
At C:\Users\jcarnovale\Desktop\Testing if.ps1:22 char:6
if (Get-ADUser -F {SamAccountName -eq $Username})
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : InvalidArgument: (:) [Get-ADUser], ArgumentException
FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.ArgumentException,Microsoft.ActiveDirectory.Management.Commands.GetADUse
You probably want to check that you have a good username before proceeding in the script, like:
$Username = $User.username
...
if(!$Username) {
throw "Username was empty!"
}
Also, try changing the Get-ADUser filter to use a string:
if (Get-ADUser -F "SamAccountName -eq $Username")
{
}
You didn't show us anything of the imported CSV file itself and I think the main problem is in there.
Import-Csv by default expects the comma (,) to be used as delimiter character. If that is not the case in your file, you need to add parameter -Delimiter followed by the character that is used as separator in your file (like -Delimiter ';' if your file uses the semicolon).
Please check that first, so the Import-Csv cmdlet can parse the file correctly.
Next, it could be that there are empty values in the username column and if so, the code should skip these rows.
Also, as commented, the -Filter parameter needs a double-quoted string "Property -eq 'something'" in which a variable like $username is expanded, instead of a scriptblock {..}
Finally, I'd recommend using Splatting on cmdlets that take many properties instead of using backticks.
Try
Import-Module ActiveDirectory
# this defaults to csv fields delimited by a comma. If your CSV file uses a different
# character, then add parameter '-Delimiter' followed by the actual character
$ADUsers = Import-Csv -Path 'C:\Users\Desktop\Powershell files\EM-mis-new-AD.csv'
# the Where-Object clause is just a precaution to omit records that have no username value
$ADUsers | Where-Object { $_.username -match '\S'} | ForEach-Object {
$Username = $_.username
if (Get-ADUser -Filter "SamAccountName -eq '$Username'" -ErrorAction SilentlyContinue) {
Write-Warning "A user account with SamAccountName '$Username' already exist in Active Directory."
}
else {
$Firstname = $_.firstname
$Lastname = $_.lastname
# use splatting on cmdlets that use a lot of parameters
$userParams = #{
SamAccountName = $Username
UserPrincipalName = "$Username#Mydomain.com"
Name = "$Firstname $Lastname"
GivenName = $Firstname
Surname = $Lastname
Enabled = $true
DisplayName = "$Firstname, $Lastname"
Path = $_.ou
AccountPassword = (ConvertTo-SecureString $_.Password -AsPlainText -Force)
ChangePasswordAtLogon = $true
}
# create the user and report back
New-ADUser #userParams
Write-Host "Created new user '$Username' with initial password: $($_.Password)"
}
}
Related
The following script is adding accounts to the Active Directory. In case the username already exists, I want to append a number to the username and try again.
i.e. if cs15csa already exists, it should try again with cs1csa2. If cs1csa2 exists, it should then try with cs1csa3 and so on and so forth.
How do I do that?
# Enter a path to your import CSV file
$ADUsers = Import-csv export.csv
foreach ($User in $ADUsers)
{
$Username = $User.username
$Password = $User.password
$Firstname = $User.firstname
$Lastname = $User.lastname
$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 ($Firstname $Lastname) already exists in the 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#iit.uni-ruse.bg" `
-Email "$Username#iit.uni-ruse.bg" `
-ProfilePath '\\leo\%USERNAME%\Profile' `
-Name "$Username" `
-GivenName $Firstname `
-Surname $Lastname `
-Enabled $True `
-DisplayName "$Firstname $Lastname" `
-Path $OU `
-AccountPassword (convertto-securestring $Password -AsPlainText -Force)
}
}
You can simply use a loop to test the SamAccountName and inside keep adding a counter number to it until you have found a unique name.
To avoid having to use those nasty backticks on the New-ADUser cmdlet, I would advise to use Splatting
Also, '\\leo\%USERNAME%\Profile' should be "\\leo\$Username\Profile"
Try
# Enter a path to your import CSV file
$ADUsers = Import-Csv export.csv
foreach ($User in $ADUsers) {
$Username = $User.username
# Check if the user account already exists in AD and keep adding
# a counter value to the SamAccountName until unique
$count = 2
while (Get-ADUser -Filter "SamAccountName -eq '$Username'") {
$Username = '{0}{1}' -f $User.username, $count++
}
# create the new user using a Splatting Hashtable
$userParams = #{
SamAccountName = $Username
UserPrincipalName = "$Username#iit.uni-ruse.bg"
EmailAddress = "$Username#iit.uni-ruse.bg"
ProfilePath = "\\leo\$Username\Profile"
Name = $Username
GivenName = $User.firstname
Surname = $User.lastname
Enabled = $true
DisplayName = '{0} {1}' -f $User.firstname, $User.lastname
Path = $User.ou
AccountPassword = $User.password | ConvertTo-SecureString -AsPlainText -Force
}
# create the user
New-ADUser #userParams
}
An alternative to the while loop above (might be faster, depending on how many similar SamAccountNames there may be in your environment) would be to do this:
# Check if the user account already exists in AD and keep adding
# a counter value to the SamAccountName until unique
# first get an array of similar SamAccountNames already present
$similarNames = #((Get-ADUser -Filter "SamAccountName -like '$Username*'").SamAccountName)
$count = 2
while ($similarNames -contains $Username) {
$Username = '{0}{1}' -f $User.username, $count++
}
I'm creating a script for adding multiple users in Active Directory. I stumbled upon this link, when I couldn't get the guide described in the question to work either. I then tried one of the solutions in the comments
Import-Module ActiveDirectory
# this defaults to csv fields delimited by a comma. If your CSV file uses a different
# character, then add parameter '-Delimiter' followed by the actual character
$ADUsers = Import-Csv -Path 'C:\Users\Desktop\Powershell files\EM-mis-new-AD.csv'
# the Where-Object clause is just a precaution to omit records that have no username value
$ADUsers | Where-Object { $_.username -match '\S'} | ForEach-Object {
$Username = $_.username
if (Get-ADUser -Filter "SamAccountName -eq '$Username'" -ErrorAction SilentlyContinue) {
Write-Warning "A user account with SamAccountName '$Username' already exist in Active Directory."
}
else {
$Firstname = $_.firstname
$Lastname = $_.lastname
# use splatting on cmdlets that use a lot of parameters
$userParams = #{
SamAccountName = $Username
UserPrincipalName = "$Username#Mydomain.com"
Name = "$Firstname $Lastname"
GivenName = $Firstname
Surname = $Lastname
Enabled = $true
DisplayName = "$Firstname, $Lastname"
Path = $_.ou
AccountPassword = (ConvertTo-SecureString $_.Password -AsPlainText -Force)
ChangePasswordAtLogon = $true
}
# create the user and report back
New-ADUser #userParams
Write-Host "Created new user '$Username' with initial password: $($_.Password)"
}
}
Here is my CSV file
firstname;lastname;username;password;ou
Mette;Frederiksen;MeFr;Password1;OU=Salg,OU=Users,OU=RGD Aarhus,DC=rgd,DC=local
Sussi;Hart;SuHa;Password1;OU=Salg,OU=Users,OU=RGD Aarhus,DC=rgd,DC=local
Ove;Tylstrup;OvTy;Password1;OU=Salg,OU=Users,OU=RGD Aarhus,DC=rgd,DC=local
Karlos;Mondolez;KaMo;Password1;OU=Lager,OU=Users,OU=RGD Aarhus,DC=rgd,DC=local
Anne;Otto;AnOt;Password1;OU=Lager,OU=Users,OU=RGD Aarhus,DC=rgd,DC=local
Dennis;Ågard;DeÅg;Password1;OU=Lager,OU=Users,OU=RGD Aarhus,DC=rgd,DC=local
Helena;Riss;HeRi;Password1;OU=Okonomi,OU=Users,OU=RGD Aarhus,DC=rgd,DC=local
Risa;Lamende;RiLa;Password1;OU=Okonomi,OU=Users,OU=RGD Aarhus,DC=rgd,DC=local
However, when I run the above code nothing happens
PS C:\Users\RGDAdmin> C:\Users\RGDAdmin\Documents\ADUser.ps1
PS C:\Users\RGDAdmin>
When I add the Delimiter parameter, I get this
Created new user 'KaMo' with initial password: Password1
New-ADUser : The directory service was unable to allocate a relative identifier
At C:\Users\RGDAdmin\Documents\ADUser.ps1:31 char:9
+ New-ADUser #userParams
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (CN=Anne Otto,OU...DC=rgd,DC=local:String) [New-ADUser], ADException
+ FullyQualifiedErrorId :
ActiveDirectoryServer:8208,Microsoft.ActiveDirectory.Management.Commands.NewADUser
PS. I know the password is bad practice in terms of passwords
Your file is delimited by semicolons, so you will definitely need to specify the -Delimiter parameter. But the documentation has a caveat:
To specify a semicolon (;) enclose it in single quotation marks.
So it should look like this:
$ADUsers = Import-Csv -Delimiter ';' -Path 'C:\Users\Desktop\Powershell files\EM-mis-new-AD.csv'
If that still results in that RID error, then there's possibly something wrong on the server. Can you create users manually using AD Users and Computers?
Try reviewing this. I don't have access to ActiveDirectory to test it myself.
#helpers
function usernameIsNotBlank {
[CmdletBinding()]
param(
$Username
)
[regex]$rx = "\S"
return $rx.match($Username)
}
function usernameDoesNotAlreadyExist {
[CmdletBinding()]
param(
$Username
)
$UserDoesNotExist = $true
$UserObject = $(
try {
Get-ADUser $Username
}
catch {
$null
}
)
if ($null -ne $UserObject) {
$UserDoesNotExist = $false
Write-Verbose "$Username already exists"
}
else {
$UserDoesNotExist = $true
}
return $UserDoesNotExist
}
function suppliedUsernameIsAvailable {
[CmdletBinding()]
param(
$Username
)
return ((usernameIsNotBlank -Username $Username) -and (usernameDoesNotAlreadyExist -Username $Username))
}
#script
$OriginalVerbose = $VerbosePreference
$VerbosePreference = "Continue"
Import-Module ActiveDirectory
$CSV = "C:\Users\Desktop\Powershell file\EM-mis-new-AD.csv"
$Data = Import-CSV $CSV
foreach ($Line in $Data) {
if (suppliedUsernameIsAvailable($Line.username)) {
New-ADUser -Name "$Line.firstname $Line.lastname" -GivenName "$Line.firstname" -Surname "$Line.lastname" -SamAccoutnname "$(Line.username)#mydomain.com" -AccountPassword (ConvertTo-SecureString $Line.password -AsPlainText -Force) -ChangePasswordAtLogon $true -Path "$Line.ou"
}
}
$VerbosePreference = $OriginalVerbose
hi there im trying to import user accounts from a CSV file to Active Directory but i've been trying for hours to no avail. Basically I have the CSV file i want to import. So I've been trying multiple powershell scripts and getting the same error
CSV contents:
GivenName,Surname,Name,SamAccountName,Path,userPrincipalName
Scooby,Doo,Scooby,Scooby,"OU=Vehicles,OU=Production,DC=csc,DC=local",scooby#csc.local
Shaggy,Rogers,Shaggy,Shaggy,"OU=Vehicles,OU=Production,DC=csc,DC=local",shaggy#csc.local
Fred,Jones,Fred,Fred,"OU=Weapons,OU=Production,DC=csc,DC=local",fred#csc.local
Daphne,Blake,Daphne,Daphne,"OU=Weapons,OU=Production,DC=csc,DC=local",daphne#csc.local
Velma,Dinkley,Velma,Velma,"OU=Weapons,OU=Production,DC=csc,DC=local",velma#csc.local
Pat,Pending,Pat,Pat,"OU=Biological,OU=Research,DC=csc,DC=local",pat#csc.local
Red,Max,Red,Red,"OU=Biological,OU=Research,DC=csc,DC=local",red#csc.local
Peneolope,Pitstop,Peneolope,Peneolope,"OU=Biological,OU=Research,DC=csc,DC=local",peneolope#csc.local
Peter,Perfect,Peter,Peter,"OU=Energy,OU=Research,DC=csc,DC=local",peter#csc.local
Rock,Slag,Rock,Rock,"OU=Energy,OU=Research,DC=csc,DC=local",rock#csc.local
Gravel,Slag,Gravel,Gravel,"OU=Energy,OU=Research,DC=csc,DC=local",gravel#csc.local
Luke,Bear,Luke,Luke,"OU=Energy,OU=Research,DC=csc,DC=local",luke#csc.local
Rufus,Ruffcut,Rufus,Rufus,"OU=Energy,OU=Research,DC=csc,DC=local",rufus#csc.local
Dick,Dastardly,Dick,Dick,"OU=Energy,OU=Research,DC=csc,DC=local",dick#csc.local
Rick,Sanchez,Rick,Rick,"OU=Board,OU=Management,DC=csc,DC=local",rick#csc.local
Morty,Smith,Morty,Morty,"OU=Board,OU=Management,DC=csc,DC=local",morty#csc.local
Beth,Smith,Beth,Beth,"OU=HR,OU=Management,DC=csc,DC=local",beth#csc.local
Powershell Script:
#Enter a path to your import CSV file
$ADUsers = Import-csv C:\scripts\csc.csv
foreach ($User in $ADUsers)
{
$Username = $User.SamAccountName
$Password = $User.Password
$Firstname = $User.Name
$Lastname = $User.Surname
$OU = $User.Path
#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
#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#csc.local" `
-Name "$Firstname $Lastname" `
-GivenName $Firstname `
-Surname $Lastname `
-Enabled $True `
-ChangePasswordAtLogon $True `
-DisplayName "$Lastname, $Firstname" `
-Path $OU `
-AccountPassword $Password `
}
}
Output from powershell:
New-ADUser : Directory object not found
At C:\scripts\Add-NewUsers.ps1:24 char:25
+ New-ADUser <<<< `
+ CategoryInfo : ObjectNotFound: (CN=Rick Sanchez...DC=csc,DC=local:String) [New-ADUser], ADIdentityN
undException
+ FullyQualifiedErrorId : Directory object not found,Microsoft.ActiveDirectory.Management.Commands.NewADUser
this error is repeated 7 times or so but the only thing different is the name (where is says ObjectNotFound(CN=Rick Sanchez..) different name for each error
Try adding this try catch block to your code, according to some googling this error is related to the OU where you want to create the new users not existing.
$ErrorActionPreference = 'Stop'
foreach ($User in $ADUsers)
{
$Username = $User.SamAccountName
$Password = $User.Password
$Firstname = $User.Name
$Lastname = $User.Surname
$OU = $User.Path
try
{
Get-ADOrganizationalUnit $OU
}
catch
{
"Creating OU: $OU"
$name, $path = $OU.Split(',',2)
New-ADOrganizationalUnit -Name $name.Replace('OU=','') -Path $path
}
# Continue script here
}
Unrelated but, you might also want to consider start using splatting on your code for obvious reasons:
$params = #{
SamAccountName = $Username
UserPrincipalName = "$Username#csc.local"
Name = "$Firstname $Lastname"
GivenName = $Firstname
Surname = $Lastname
Enabled = $True
ChangePasswordAtLogon = $True
DisplayName = "$Lastname, $Firstname"
Path = $OU
AccountPassword = $Password
}
New-ADUser #params
For a school project, i need to make a Powershell script, but to create a username, with only the first letter of the person name, and the full second name, could anyone help me with this? This is what i currently have:
Import-Module ActiveDirectory
# password for accounts
$securePassword = ConvertTo-SecureString "Welkom#1" -AsPlainText -Force
# Import the file into a variable
$users = Import-Csv -Path .\New-GaastraUserBulk.csv
# Loop trough each row, and gather Information
ForEach ($user in $users) {
# Gather the user Information
$fname = $user.FirstName
$lname = $user.LastName
$jtitle = $user.JobTitle
$OUpath = $user.OU
Write-Host $fname
Write-Host $lname
Write-Host $jtitle
Write-Host $OUpath
#Gebruiker aanmaken in AD
New-ADUser -Name "$fname $lname" -GivenName $fname -SamAccountName $lname -Surname $lname -UserPrincipalName "$lname" -Path $OUpath -AccountPassword $securePassword -PasswordNeverExpires $true -Enabled $true
}
As per the comments from others. Add this line after $lname = ...
$sam = "{0}$lname" -f $fname.Substring(0,1)
Then edit your New-ADUser line use $sam
New-ADUser .... -SamAccountName $sam ...
Turning my comment into an answer.
You can create the user's SamAccountName quite easily, combining the first character of the users GivenName with the full LastName. However, you need to check that this SamAccountName is not already in use.
Another thing is that the UserPrincipalName should be in the form of <user>#<DNS-domain-name>.
To improve your code also using Splatting:
Import-Module ActiveDirectory
# password for accounts
$securePassword = ConvertTo-SecureString "Welkom#1" -AsPlainText -Force
# Import the file into a variable
$users = Import-Csv -Path .\New-GaastraUserBulk.csv
# Loop trough each row, and gather Information
foreach ($user in $users) {
# first create the desired SamAccountName for the new user
$accountName = "{0}{1}" -f $user.FirstName.Substring(0,1),$user.LastName
# test if a user with that SamAccountName already exists
$checkUser = Get-ADUser -Filter "SamAccountName -eq '$accountName'" -ErrorAction SilentlyContinue
if ($checkUser) {
Write-Warning "SamAccountName $accountName already used for user $($checkUser.Name)"
}
else {
# create a hashtable with all parameters for the New-ADUser cmdlet
$userParams = #{
Name = "$fname $lname"
GivenName = $user.FirstName
Surname = $user.LastName
Title = $user.JobTitle
SamAccountName = $accountName
Path = $user.OU
AccountPassword = $securePassword
PasswordNeverExpires = $true
Enabled = $true
UserPrincipalName = "$accountName#yourdomain.com" # <-- put YOUR domain here after the '#'
# other parameters go here if needed
}
New-ADUser #userParams
}
}
Also, keep in mind that you cannot use just any character for a SamAccountName.
Characters " [ ] : ; | = + * ? < > / \ , # are illegal, aswell as non-printable characters and the dot . can not be the last character of the name.
AND, the system limits sAMAccountName to 20 characters for user objects.
To make sure, use something like:
$accountName = ($accountName -replace '["\[\]:; |=+\*\?<>/\\,#]').TrimEnd(".") -replace '^(.{1,20}).*', '$1'
I can't import users in powershell with a script via an csv file, but If I print the parameters on the screen,it shows them as it should.
what I am doing wrong? in my life plenty with that mustache, but plis focus on the script.
is running windows server 2016 on the powershell ise, on virtualbox
The Script:
If(-Not(Get-ADOrganizationalUnit -Filter {Name -eq "991-5D"}))
{New-ADOrganizationalUnit "991-5D" -Path (Get-ADDomain).DistinguishedName}
If(-Not(Get-ADOrganizationalUnit -Filter {Name -eq "911-5V"}))
{New-ADOrganizationalUnit "911-5V" -Path (Get-ADDomain).DistinguishedName}
$domain=(Get-ADDomain).DNSRoot
Import-Csv -Path "C:\Alumnos.csv" | foreach-object {
[int]$number= $_.X
If($number -ge 10 -and $number -le 26)
{
$UO="991-5D"
}
//there are many others O.U.
$ou= "UO="+$UO+","+$domain
$UPN = $_.LETRA+$_.PATERNO+$_.X+"#"+ "$domain"
$CUENTA= $_.LETRA+$_.PATERNO+$_.X
New-ADUser -SamAccountName $CUENTA -UserPrincipalName $CUENTA -Name $_.NOMBRE
-SurName $_.PATERNO -GivenName $_.NOMBRE -EmailAddress $UPN -AccountPassword
(ConvertTo-SecureString "Leica666" -AsPlainText -force) -Path $ou
-Enabled $true -ChangePasswordAtLogon $true -Verbose}
the data:
X,PATERNO,MATERNO,NOMBRE,SEGUNDO,LETRA
10,ARÉVALO,CORNEJO,NICOLÁS,ALEJANDRO,N
11,BARRIOS,MONTERO,BENJAMÍN,IGNACIO,B
12,BUSTAMANTE,LOYOLA,IGNACIO,HERNANDO,I
13,BUSTOS,GARRIDO,ARTURO,IGNACIO,A
this are the results on each line:
+ New-ADUser -SamAccountName $CUENTA -UserPrincipalName $CUENTA -Name $ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo:NotSpecified: (CN=IGNACIO,UO=9...da.com:String)
[New-ADUser], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:8335,
Microsoft.ActiveDirectory.Management.Commands.NewADUser
the head:
X,PATERNO,MATERNO,NOMBRE,SEGUNDO,LETRA
echo:
#{X=42; PATERNO=PAYACÁN; MATERNO=ZAPATA; NOMBRE=NICOLÁS; SEGUNDO=N; LETRA=}.NOMBRE
I know that reads the file and instead of reading just the column reads all the line($_), and then prints whatever I wrote next to it(".name", ".section", etc).
I've made some variable and format changes to make this code more successful.
$domain=Get-ADDomain
Import-Csv -Path "C:\Alumnos.csv" |
Foreach-Object {
[int]$number= $_.X
If($number -ge 10 -and $number -le 26)
{
$UO="991-5D"
}
$ou = "OU={0},{1}" -f $UO,$domain.DistinguishedName
$UPN = "{0}{1}{2}#{3}" -f $_.LETRA,$_.PATERNO,$_.X,$domain.DNSRoot
$CUENTA= "{0}{1}{2}" -f $_.LETRA,$_.PATERNO,$_.X
New-ADUser -SamAccountName $CUENTA -UserPrincipalName $UPN -Name $_.NOMBRE `
-SurName $_.PATERNO -GivenName $_.NOMBRE -EmailAddress $UPN `
-AccountPassword (ConvertTo-SecureString "Leica666" -AsPlainText -force) -Path $ou `
-Enabled $true -ChangePasswordAtLogon $true -Verbose
}
Explanation:
$domain: I've made this an ADDomain object. This allows the DistinguishedName and DNSRoot properties to be accessed where appropriate.
-f operator: I used the format operator to make it easier to read the string concatenation attempts.
$ou: This is constructed using the DistinguishedName of the domain. This is the proper format for the OU path.
$UPN: This is constructed using the DNSRoot of the domain. It can obviously be different than your domain, but must be in an email address or FQDN format.
Additional Comments:
You are setting -Name to be $_.NOMBRE. This could be problematic because Name must be unique in each OU. Name is used to build the CN, which is where uniqueness is required. If you have NICOLAS in OU 991-5D, you are going to get an error if you try to create another NICOLAS in the same place. IMHO, I would do something different. You could also implement the use of splatting for building the properties of your New-ADUser command, but that is only for readability purposes. Below is an example of splatting:
$NewUserProperties = #{
SamAccountName = $CUENTA
UserPrincipalName = $UPN
Name = $_.NOMBRE
Surname = $_.PATERNO
GivenName = $_.NOMBRE
EmailAddress = $UPN
AccountPassword = (ConvertTo-SecureString "Leica666" -AsPlainText -force)
Path = $ou
Enabled = $true
ChangePasswordAtLogon = $true
}
New-ADUser #NewUserProperties -Verbose