Importing users from CSV into AD with PowerShell - 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,

Related

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>"

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 }

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!

New-ADUser : Cannot bind parameter because parameter 'co' is specified more than once

I saw some questions which has kinda the same title, but none of them solved my problem, I don't get why I get this error. Here's my code :
$NORMAL_ACCOUNTS = Import-Excel -Path "data_norm.xlsx"
$TEMPLATE_NORMAL_ACCOUNT = Get-ADUser anUser -Properties c, CN, co, Company, Country, Description, DisplayName, DistinguishedName, employeeType, GivenName, Manager, Name, Organization, otherMailbox, preferredLanguage, PrimaryGroup, SamAccountName, sn, StreetAddress, Surname, Title, UserPrincipalName
$TEMPLATE_NORMAL_ACCOUNT.UserPrincipalName = $NULL
$OTHER_EMAIL = $NULL
FOREACH($NORMAL in $NORMAL_ACCOUNTS)
{
$OTHER_EMAIL = #("$($NORMAL.otherMailbox)")
New-ADUser `
-Instance $TEMPLATE_NORMAL_ACCOUNT `
-c "$($NORMAL.c)" `
-CN "$($NORMAL.CN)" `
-co "$($NORMAL.co)" `
-Company "$($NORMAL.Company)" `
-Country "$($NORMAL.Country)" `
-Description "$($NORMAL.Description)" `
-DisplayName "$($NORMAL.DisplayName)" `
-DistinguishedName "$($NORMAL.DistinguishedName)" `
-employeeType "$($NORMAL.employeeType)" `
-GivenName "$($NORMAL.GivenName)" `
-Manager "$($NORMAL.Manager)" `
-Name "$($NORMAL.Name)" `
-Organization "$($NORMAL.Organization)" `
-otherMailbox $OTHER_EMAIL `
-preferredLanguage "$($NORMAL.preferredLanguage)" `
-PrimaryGroup "$($NORMAL.PrimaryGroup)" `
-SamAccountName "$($NORMAL.SamAccountName)" `
-sn "$($NORMAL.sn)" `
-StreetAddress "$($NORMAL.StreetAddress)" `
-Surname "$($NORMAL.Surname)" `
-Title "$($NORMAL.Title)" `
-UserPrincipalName "$($NORMAL.UserPrincipalName)" `
-AccountPassword (Read-Host -AsSecureString "INPUT USER PASSWORD") `
-Enabled $FALSE
}
And I get (in French) this error :
New-ADUser : Impossible de lier le paramètre, car le paramètre «co» est spécifié plusieurs fois. Pour fournir plusieurs valeurs aux paramètres qui les
acceptent, utilisez la syntaxe de tableau. Par exemple, «-parameter valeur1,valeur2,valeur3».
Au caractère D:\Users\pmonties\OneDrive - Professional\Documents\VARONIS - I-TRACING\CREATE_ACCOUNTS.ps1:22 : 9
+ -co "$($NORMAL.co)" `
+ ~~~
+ CategoryInfo : InvalidArgument : (:) [New-ADUser], ParameterBindingException
+ FullyQualifiedErrorId : ParameterAlreadyBound,Microsoft.ActiveDirectory.Management.Commands.NewADUser
I tried to remove the "co" attribute part from the code, and then I get this error :
A positional parameter cannot be found that accepts argument “FR”
Any ideas ?

Bulk Add AD through Powershell/CSV issue

I am trying to bulk-add users into my Active Directory, but I am getting expression errors right at the start of the script. I am not a script buff at all, so I am really out of ideas from the get go.
$Users = Import-Csv ".\UsersFile.csv"
foreach ($User in $Users)
{
-OrganizationalUnit $User.OU
-SamAccountName $User.UserName
-userPassword $User.Password
-GivenName $User.First
-Initials $USer.Initial
-sn $User.Last
-Displayname $User.DisplayName
-Description $User.Description
-Physicaldeliveryofficename $User.Office
-TelephoneNumber $User.Tel
-Mail $User.mail
-streetaddress $User.Street
-postOfficeBox $User.Postbus
-l $User.Location
-st $User.Provincie
-postalCode $User.Postcode
-c $User.Land
-deparment $User.Department
-Company $User.Organisatie
-Manager $User.Manager
-Password $User.Password -ResetPasswordOnNextLogon $false
}
The error log.
Missing expression after unary operator '-'.
At C:\Users\Administrator\Desktop\CreateUserBulk.ps1:4 char:10
+ - <<<< OrganizationalUnit $User.OU `
+ CategoryInfo : ParserError: (-:String) [], Parseexception
+ FullyQualifiedErrorID : MissingExpressionAfterOperator
After trying the link (From serv) and editing the CSV and script accordingly, getting a lot more errors now with this.
Import-Csv : Cannot open file "C:\Users\administrator\UsersFile.csv".
At C:\Users\administrator\Desktop\Untitled3.ps1:2 char:20
+ $Users = Import-Csv <<<< -Delimiter ";" -Path ".\UsersFile.csv"
+ CategoryInfo : OpenError: (:) [Import-Csv], FileNotFoundException
+ FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.ImportCsvCommand
You cannot call a method on a null-valued expression.
At C:\Users\administrator\Desktop\Untitled3.ps1:9 char:53
+ $FirstLetterFirstname = $UserFirstname.substring <<<< (0,1)
+ CategoryInfo : InvalidOperation: (substring:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
ConvertTo-SecureString : Cannot bind argument to parameter 'String' because it is null.
At C:\Users\administrator\Desktop\Untitled3.ps1:11 char:195
+ New-ADUser -Name $Detailedname -SamAccountName $SAM -UserPrincipalName $SAM -DisplayName $Detailedname -GivenName
$user.firstname -Surname $user.name -AccountPassword (ConvertTo-SecureString <<<< $Password -AsPlainText -Force) -Ena
bled $true -Path $OU
+ CategoryInfo : InvalidData: (:) [ConvertTo-SecureString], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ConvertToSe
cureStringCommand
EDIT2: Fixed, I changed the source link to it's fullness and now it works!
You are not creating a new AD user in your script. So -OrganizationalUnit should be undefined and throw an error, excpet you declare them as a variable first.
Import-Module ActiveDirectory
$Users = Import-Csv -Delimiter ";" -Path ".\UsersFile.csv"
foreach ($User in $Users)
{
$FirstLetterFirstname = $User.firstname.substring(0,1)
New-ADUser -Name $User.firstname + " " + $User.name
-SamAccountName $FirstLetterFirstName + $User.name
//... and so on
}
You can declare all variables first in the manner of $FirstletterFirstName and execute the New-ADUser command at the end of each loop, which makes it easier to read and modify later on.
The important part stays: Adding a new user is executed through the New-ADUser command which you are missing. You can also add the New-ADUser to the top of your loop, which should make your query work if there are no other syntax errors / Spelling errors in your code
//EDIT: You can find a working example at http://gallery.technet.microsoft.com/scriptcenter/ed20b349-9758-4c70-adc0-19c5acfcae45
and the TechNet article for New-ADUser:
http://technet.microsoft.com/en-us/library/ee617253.aspx