script to create new AD user fails - powershell

I would like to atomate the user account creation with a CSV file.
I have done some tests but it stills fails.
# Import active directory module for running AD cmdlets
Import-Module activedirectory
$log = "log.txt"
#Store the data from ADUsers.csv in the $ADUsers variable
$ADUsers = Import-csv C:\Scripts\newusers.csv -Delimiter ";"
#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
echo = $Firstname
#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#axpenet.local" `
-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
}
}
If i then run the script I get the following errors
New-ADUser : No se puede validar el argumento del parámetro 'Path'. El argumento es null o está vacío. Proporcione un argumento que no sea null o que no
esté vacío e intente ejecutar el comando de nuevo.
En C:\Scripts\newpipol.ps1: 50 Carácter: 19
+ -Path $OU `
+ ~~~
+ CategoryInfo : InvalidData: (:) [New-ADUser], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.NewADUser
ConvertTo-SecureString : No se puede enlazar el argumento al parámetro 'String' porque es nulo.
En C:\Scripts\newpipol.ps1: 59 Carácter: 54
+ ... -AccountPassword (convertto-securestring $Password -AsPlai ...
+ ~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [ConvertTo-SecureString], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ConvertToSecureStringCommand
So I think that the New-ADUser command is not picking up the variables values from above.
How can I do to for example set a breakpoint somewhere to see the value of a variable on a specific point of the script?

Related

how to update custom attribute in active directory?

Hi guys my name is Bastian and I am a student. I come to ask for help on a script to update users in active directory with CSV file. I created the columns in the active directory schema, all appear in the user profile when I look for them, but when I perform the update the message says that the parameter does not exist. The updates through PowerShell directly works and is reflected, but through the CSV file does not find the columns, I need your help to correct my error, I would appreciate your guidance.
Import-Module ActiveDirectory
[String]$Ruta = Read-Host "path (Por Ejemplo
C:\archivocsv.csv)"
$ou="OU=DominioExtendido" + "," + (Get-ADDomain).DistinguishedName
If(-Not(Get-ADOrganizationalUnit -Filter {Name -eq "DominioExtendido"})){New-ADOrganizationalUnit
"DominioExtendido" -Path (Get-ADDomain).DistinguishedName}
$dominio=(Get-ADDomain).DNSRoot
Import-Csv -Path $Ruta | foreach-object {
$UPN = $_.Cuenta + "#" + "$dominio"
New-ADUser -SamAccountName $_.Cuenta -UserPrincipalName $UPN -Name $_.Nombre -DisplayName
$_.Nombre -SurName $_.Apellidos -GivenName $_.Nombres -Description $_.Descripcion -Office
$_.Oficina -OfficePhone $_.Telefono -EmailAddress $_.Email -Title $_.Titulo -Department
$_.Departamento -Company $_.Compania -City $_.Ciudad -State $_.Region -AccountPassword
(ConvertTo- SecureString $_.Clave -AsPlainText -force) -Path $ou -Enabled $true -
ChangePasswordAtLogon $true -Verbose -companyCode $_.CodigoEmpresa -companyID $._RutEmpresa -
socialReason $._razonSocial -acronymCountryCode $._CodigoPais -contractType $._TipoContrato -
businessUnity $._BU -officeLicence $._Licencia365}
""
finish!!
PS C:> ErrorTerminación(New-ADUser): "No se encuentra ningún parámetro que coincida con el nombre del
parámetro 'companyCode'." New-ADUser : No se encuentra ningún parámetro que coincida con el
nombre del parámetro 'companyCode'. En C:\Creacion_Masiva_Usuarios.ps1: 15 Carácter: 473+ ...
$true -Verbose - companyCode $_.Codigo_Empresa -companyID $._Rut_Empresa -socialR ...
CategoryInfo : InvalidArgument: (:) [New-ADUser], ParameterBindingException
FullyQualifiedErrorId :
NamedParameterNotFound,Microsoft.ActiveDirectory.Management.Commands.NewADUser
User attributes
Profile user
Use New-ADUser -OtherAttributes for attributes that don't have a corresponding parameter!
The -OtherAttributes parameter takes a hashtable as an argument, and you simply populate it with key-value entries where the key is the attribute display name and the value is the intended attribute value.
For an attribute with the display name companyCode, you'd supply a hashtable like this:
New-ADUser ... -OtherAttributes #{ 'companyCode' = $_.CodigoEmpresa }

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

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

Why am I getting a "missing expression" error in my PS New-ADUser script?

The error I'm getting is "Missing expression after unary operator '-'" At line 63, char 14. So it's where the Path/OU is set, but I can't find anything wrong with it. Any help is appreciated. Thanks.
# 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:\ADMaint\NewUsers\NewUsers.csv
$Password = "Welcome01"
$OU = "ou=NewUsers,ou=Users,ou=Logins,dc=company,dc=com"
#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
$Firstname = $User.firstname
$Middle = $User.middle
$Lastname = $User.lastname
$Department = $User.department
$Title = $User.title
$Office = $User.office
$Address = $User.address
$Company = $User.company
$employeeNumber = $User.employeeNumber
$employeeID = $User.employeeID
$Telephone = $User.telephone
$Pager = $User.pager
$Mobile = $User.mobile
$Fax = $User.fax
$Custom1 = $User.custom1
$Custom2 = $User.custom2
$Custom3 = $User.custom3
$Custom4 = $User.custom4
$DisplayName = "$Lastname" + ", " + "$Firstname" + " " + "$Middle"
$Username = "$lastname".ToLower() + "$firstname".substring(0,1).ToLower()
#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#vinfen.org" `
-Name $DisplayName `
-GivenName $Firstname `
-surname $Lastname `
-initials $Middle `
-department $Department `
-title $Title `
-Office $Office `
-streetAddress $Address `
-Company $Company `
-employeeNumber $EmployeeNumber `
-employeeID $EmployeeID `
-OfficePhone $Telephone `
-mobile $Mobile `
-fax $Fax `
-DisplayName $DisplayName`
-Path $OU `
-AccountPassword (convertto-securestring $Password -AsPlainText -Force) `
#-OtherAttribute #{pager="$(User."pager")"; extensionAttribute1="$(User."custom1")"; extensionAttribute2="$(User."custom2")"; extensionAttribute3="$(User."custom3")"; extensionAttribute4="$(User."custom4")"} `
-ChangePasswordAtLogon $true `
-Enabled $true `
}
}
Can't verify now, but looks like there is a missing space before the ` on the previous line.
-DisplayName $DisplayName`
Multi-line commands require the space before the ` symbol.