how to update custom attribute in active directory? - powershell

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 }

Related

How to resolve NewAD error with -Path $OU

I am currently trying to automate the creation of new users on my Active Directory.
However when I run my powershell here is the error that presents itself to me :
New-ADUser: Unable to validate argument on "Path" parameter. The argument is null or empty. Provide an argument that is not null or empty and try again.
At character Line: 23:19
+ -Path $ OR `
+ ~~~
+ CategoryInfo: InvalidData: (:) [New-ADUser], ParameterBindingValidationException
+ FullyQualifiedErrorId: ParameterArgumentValidationError, Microsoft.ActiveDirectory.Management.Commands.NewADUser
What can i do ?
Thanks for your help !
This is my code
$ADUsers = Import-csv E:\SCRIPT\newusers.csv
foreach ($User in $ADUsers)
{
$Username = $User.username
$Password = $User.password
$Firstname = $User.firstname
$Lastname = $User.lastname
$Description = $User.description
$OU = $User.ou
New-ADUser `
-SamAccountName $Username `
-UserPrincipalName "$Lastname#domaine.fr" `
-Name "$Firstname $Lastname" `
-GivenName $Firstname `
-Surname $Lastname `
-Enabled $True `
-ChangePasswordAtLogon $False `
-DisplayName "$Lastname, $Firstname" `
-Description $Description `
-AccountPassword $Password `
-Path $OU `
}
Your comment indicates the CSV file uses the ; semi-colon as delimiter character, but you neglect to add that to the Import-Csv cmdlet. Now it is trying to parse the data using the default comma , and because of that none of the fields have a correct value.
Replace the first line with
$ADUsers = Import-csv -Path 'E:\SCRIPT\newusers.csv' -Delimiter ';'
Other than that, have a look at using splatting, so you don't need those awkward backticks.

Import-Module ActiveDirectory powershell error

I am creating a script that asks the user for the first and last name and implements it in a group in Active Directory. Below shows how the script starts
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"
The text below shows the body of the script where the information is put
New-ADUser `
-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 "<path>"
I get an error that is shown below showing that objects are not found. The errors are shown below
-Name$firstName $lastName : The term '-Name$firstName $lastName' 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 line:9 char:5
+ -Name"$firstName $lastName" `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (-Name$firstName $lastName:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
-EmailAddress : The term '-EmailAddress' 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 line:13 char:5
+ -EmailAddress "$firstName.$lastName#irtc-tx.com"
+ ~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (-EmailAddress:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
-ChangePasswordAtLogon : The term '-ChangePasswordAtLogon' 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 line:14 char:5
+ -ChangePasswordAtLogon 1 `
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (-ChangePasswordAtLogon:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
I have checked spelling and that doesnt seem to be an issue. Is there an obvious mistake I am making?
This looks like you have a space after the backtick character. That is the danger of using that to do line breaks. A better way to do that if you like how it is organized better is to define a hashtable, then splat that to the cmdlet like this:
$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 = "<path>"
}
New-ADUser #UserParams
Remove trailing whitespaces after backticks (`) and place missing ones :)
New-ADUser `
-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 "<path>"
Your example shows a space between -name and "$firstName $lastName" but the error shows differently. Double check that there's a space
You're also missing some backticks, one after the UserPrincipalName line and one after emailaddress line and you have an extra space after the first backtick.
New-ADUser `
-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 "<path>"

Adding users via powershell script gives error

I am trying to ad users from a csv file to an OU with a powershell script but getting some error?
I'll post the line that I am using for adding the users. And I have checked that the retrieval path for the csv file is correct..
New-ADUser -SamAccountName $login -Name $namn -GivenName $Fname -Surname $Enamn -Department $user.Department -Division $user.Division -Title $user.role -Description $user.Extension -Office $user.Office -UserPrincipalName $login"#hqad.local" -path "OU=Carb_users,DC=HQAD,DC=Local" -EmailAddress $mail -AccountPassword (ConvertTo-SecureString -AsPlainText "Syp9393" -Force) -Enable $True
Error output:
New-ADUser : The server is unwilling to process the request
At C:\Users\Administrator\Desktop\Userscript.ps1:37 char:1
+ New-ADUser -SamAccountName $login -Name $namn -GivenName $Fname -Surn ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (CN=Carl Malm,OU...C=HQAD,DC=Local:String) [New-ADUser], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:0,Microsoft.ActiveDirectory.Management.Commands.NewADUser
Happy for any help!

script to create new AD user fails

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?

Importing users from CSV into AD with PowerShell

I'm using the following script in order to import 100,000 users from a CSV file into Active Directory. However, I'm getting a lot of errors and need your help in eliminating them.
Script:
Import-Csv C:\csv\100Kusers.csv | ForEach-Object {
$userPrinc = $_."Logon Username" + "#mydomain.com"
New-QADUser -Name $_.Name `
-ParentContainer $_."Container" `
-SamAccountName $_."Logon Username" `
-UserPassword "passw0rd123" `
-FirstName $_.FirstName `
-LastName $_."LastName" `
-Description $_."Department" `
-UserPrincipalName $userPrinc `
-DisplayName $_."Name" `
-StreetAddress $_."StreetAddress" `
-City $_."City" `
-State $_."State" `
-PostalCode $_."PostalCode" `
-Email $_."Email" `
-Company $_."Company" `
-Department $_."Department" `
-HomePhone $_."HomePhone" `
-Title $_."Title" `
-Manager $_."Manager" ;`
Add-QADGroupMember -identity $_."Group" -Member $_."Logon Username" ;`
}
And here are the errors I'm getting:
Add-QADGroupMember : Cannot resolve directory object for the given identity: 'jm?lmhx4'.
At C:\csv\PS_import_script.ps1:22 char:2
+ Add-QADGroupMember -identity $_."Group" -Member $_."Logon Username" ;`
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Add-QADGroupMember], ObjectNotFoundException
+ FullyQualifiedErrorId : Quest.ActiveRoles.ArsPowerShellSnapIn.DirectoryAccess.ObjectNotFoundException,Qu
est.ActiveRoles.ArsPowerShellSnapIn.Commands.AddGroupMemberCmdlet2
New-QADUser : A device attached to the system is not functioning.
At C:\csv\PS_import_script.ps1:3 char:2
+ New-QADUser -Name $_.Name `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [New-QADUser], DirectoryServicesCOMException
+ FullyQualifiedErrorId : System.DirectoryServices.DirectoryServicesCOMException,Quest.ActiveRoles.ArsPowerShellSnapIn.Powershell.Cmdlets.NewUserCmdlet
CSV looks like this:
FirstName Surname Name StreetAddress City State PostalCode EmailAddress Company Department Group HomePhone Title Manager Logon Username Container
Jose Mullane Jose Mul Rue de Li?ge 493 Lompret WLX 6463 JoseLMullane#superrito.com rmit QA QA-FL 0495 94 79 62 Laboratory animal technologist tgatesjr jmuljhk2 dcui.mydomain.com/dcui_OU/Finland/Departments/QA
Sorry, can't add more - formatting goes crazy when I copy a plain CSV into the post window.
Many thanks everyone. I agree that this could be an encoding issue and yes, the CSV itself had all those off "?" marks, after I saved it from xlsx format. We ended up using Pyhthon, which also was much faster, comparing to Pshell.
Yours,