Bulkuser creation in AD using powershell - powershell

I am trying to upload bulk users to my AD using the code below.
But it keep giving me an error.
import-csv C:\Users\Administrator\Desktop\properties1.csv |ForEach-Object {New-ADUser -path "OU=Users,OU=ICTLAB,DC=gdgshj,DC=com" -UserPrincipalName $_.UserPrincipalName -SamAccountName $_.SamAccountName -GivenName $_.GivenName -Name $_.Name -DisplayName $_.DisplayName -profilepath $_.Profilepath Set-ADAccountPassword -Identity $_.SamAccountName -Reset -NewPassword (ConvertTo-SecureString -AsPlainText $_.Password -Force) Enable-ADAccount -Identity $_.SamAccountName }
The error is as attached.

You need a statement terminator for the New-ADUser cmdlet, before calling Set-ADAccountPassword.
You can either use ;, or place Set-ADAccountPassword on a separate line:
Import-Csv C:\Users\Administrator\Desktop\properties1.csv |ForEach-Object {
New-ADUser -path "OU=Users,OU=ICTLAB,DC=gdgshj,DC=com" -UserPrincipalName $_.UserPrincipalName -SamAccountName $_.SamAccountName -GivenName $_.GivenName -Name $_.Name -DisplayName $_.DisplayName -profilepath $_.Profilepath
Set-ADAccountPassword -Identity $_.SamAccountName -Reset -NewPassword (ConvertTo-SecureString -AsPlainText $_.Password -Force)
Enable-ADAccount -Identity $_.SamAccountName
}
You can also chain the commands together in a single pipeline, if you use the -PassThru switch on New-ADUser and Set-ADAccountPassword (notice the | at the end of each line):
Import-Csv C:\Users\Administrator\Desktop\properties1.csv |ForEach-Object {
New-ADUser -path "OU=Users,OU=ICTLAB,DC=gdgshj,DC=com" -UserPrincipalName $_.UserPrincipalName -SamAccountName $_.SamAccountName -GivenName $_.GivenName -Name $_.Name -DisplayName $_.DisplayName -profilepath $_.Profilepath -PassThru |
Set-ADAccountPassword -Reset -NewPassword (ConvertTo-SecureString -AsPlainText $_.Password -Force) -PassThru |
Enable-ADAccount
}

Related

can't create userS via powershell

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

Adding newly created users to pre-existing groups

This script currently creates new users after importing data from a CSV file
Import-Module ActiveDirectory
Import-Csv "C:\testcsv.csv" | ForEach-Object {
$userPrincinpal = $_."samAccountName" + "#NWTC.local"
New-ADUser -Name $_.Name `
-Path $_."ParentOU" `
-SamAccountName $_."samAccountName" `
-UserPrincipalName $userPrincinpal `
-AccountPassword (ConvertTo-SecureString "Password1" -AsPlainText -Force) `
-ChangePasswordAtLogon $false `
-Enabled $true
}
This is the csv file I am importing from:
Name,samAccountName,ParentOU,Group
Test Test1,TTest1,"OU=Business,DC=NWTC,DC=local",TestGroup
After a user is created, I want to add them to an already exisiting group. There will be different groups I want different users to be added to, but only 1 group per person.
I've been playing around with Add-AdGroupMember, but I'm not sure how to proceed. Something like this: Add-ADGroupMember -Members $_.Members. This is the first time I'm working with CSVs, so I'm in new territory
New-ADuser does not support this functionality so you will have to do that yourself after the fact. What you could do is have New-ADUser spit out the AD user object it creates and use that with Add-ADGroupMember.
$newUserProperties = #{
Name = $_.Name
Path = $_."ParentOU"
SamAccountName = $_."samAccountName"
UserPrincipalName = $_."samAccountName" + "#NWTC.local"
AccountPassword = (ConvertTo-SecureString "Password1" -AsPlainText -Force)
ChangePasswordAtLogon = $false
Enabled = $true
}
try{
$newADUser = New-ADUser #newUserProperties -PassThru
Add-ADGroupMember -Identity $_.Group -Members $newADUser.SamAccountName
} catch {
Write-Warning "Could not create $($newUserProperties.samaccountname)"
}
The error handling is crude but should exist in some form to account for failures in the source data or misconceptions of existing users. Basically just getting $newADUser and using it for Add-ADGroupMember
We use splatting of the parameters here. That way you don't have to worry about having nice formatted code by using backticks.
Add the Add-ADGroupMember in the ForEach-Object after the new user is created :
Import-Module ActiveDirectory
Import-Csv "C:\testcsv.csv" | ForEach-Object {
$userPrincinpal = $_."samAccountName" + "#NWTC.local"
New-ADUser -Name $_.Name `
-Path $_."ParentOU" `
-SamAccountName $_."samAccountName" `
-UserPrincipalName $userPrincinpal `
-AccountPassword (ConvertTo-SecureString "Password1" -AsPlainText -Force) `
-ChangePasswordAtLogon $false `
-Enabled $true
Add-ADGroupMember -Identity 'AD_GROUP_WHERE_YOU_ADD_MEMBERS' -Members $_.samAccountName
}

exchange 2013 bulk create mailboxes error

I am trying to import a list of users from a csv file and I get the following error:
script:
PS C:\Software> import-csv C:\Software\lastDumpPolished.csv | % {
New-ADUser -Name $_.Name -SamAccountName $_.SamAccountName `
-DisplayName $_.Name -Surname $_.Sn -GivenName $_.GivenName `
-AccountPassword (ConvertTo-SecureString password1234 `
-AsPlainText -Force) -Enabled:$true -Title $_.Title `
-Description $_.describtion -Company Myland `
-OfficePhone $_.Telephone -HomeDrive Z: `
-HomeDirectory $homedrive -ChangePasswordAtLogon:$true `
} | Enable-Mailbox -Identity $_.SamAccountName -Alias $_.SamAccountName
Error:
Enable-Mailbox : Cannot bind argument to parameter 'Identity' because it is null.
At line:1 char:443
+ ... lbox -Identity $_.SamAccountName -Alias $_.SamAccountName
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Enable-Mailbox], ParameterBind
ingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,M
icrosoft.Exchange.Management.RecipientTasks.EnableMailbox
Powershell doesn't remember $_.SamAccountName for some reason.
It there an easy 'inline method' of setting it to a variable that can be used after the pipe?
How do I get rid of that error so I can create and enable the mailboxes in bulk?
import-csv C:\Software\lastDumpPolished.csv | % {
New-ADUser -Name $_.Name -SamAccountName $_.SamAccountName `
-DisplayName $_.Name -Surname $_.Sn -GivenName $_.GivenName `
-AccountPassword (ConvertTo-SecureString password1234 `
-AsPlainText -Force) -Enabled:$true -Title $_.Title `
-Description $_.describtion -Company Myland `
-OfficePhone $_.Telephone -HomeDrive Z: `
-HomeDirectory $homedrive -ChangePasswordAtLogon:$true `
} | % { Enable-Mailbox -Identity $_.SamAccountName -Alias $_.SamAccountName }

Powershell Import-Csv New-AdUser skip if user exists

I have a fully functional script to import and create AD Users, but I would like to skip from attempting to create Users that are already in AD.
Import-Module ActiveDirectory
$CsvPath = "C:\Shares\Users.csv"
$CsvTest = Test-Path $CsvPath
Import-Csv $CsvPath | ForEach-Object {
Get-AdUser $_.sAMAccountName
}
Import-Csv $CsvPath | ForEach-Object {
New-ADUser -Name $_.Name -UserPrincipalName $_.userPrincipalName -SamAccountName $_.sAMAccountName -DisplayName $_.DisplayName -GivenName $_.GivenName -Surname $_.Surname -AccountPassword (ConvertTo-SecureString $_.Password -AsPlainText -force) -Enabled $true -ChangePasswordAtLogon $true
{
Catch [Microsoft.ActiveDirectory.Management.Commands.NewADUser]
}
$_."sAMAccountName"; "already exists"
}
Something like this without relying on exceptions would be better:
Import-Module ActiveDirectory
$csvPath = "C:\Shares\Users.csv"
if (Test-Path $csvPath)
{
$newUsers = Import-Csv $csvPath
$existingUsers = Get-ADGroupMember "Domain Users"
foreach ($newUser in $newUsers)
{
if (($existingUsers | Where-Object { $_.sAMAccountName -eq $newUser.sAMAccountName }) -eq $null)
{
$user = New-ADUser -Name $newUser.Name -UserPrincipalName $newUser.userPrincipalName -SamAccountName $newUser.sAMAccountName -DisplayName $newUser.DisplayName -GivenName $newUser.GivenName -Surname $newUser.Surname -AccountPassword (ConvertTo-SecureString $newUser.Password -AsPlainText -Force) -Enabled $true -ChangePasswordAtLogon $true
}
}
}
Personally I prefer to use the Quest AD Module for Powershell as it avoids exceptions by returning $null when an object doesn't exist.

Powershell new-aduser attribute was not in the acceptable range

I'm having an issue with the following Powershell script. It is
a value for the attribute was not in the acceptable range of values Line 1 char 59
Import-Csv .\tableofusers.csv | foreach-object {New-ADUser -Path "ou=ou,dc=dc" -SamAccountName $_.SamAccountName -Name $_.name -DisplayName $_.name -GivenName $_.gn -SurName $_.sn -StreetAddress $_.SA -city $_.city -state $_.state -PostalCode $_.PostalCode -Country $_.Country -officephone $_.officephone -emailaddress $_.emailaddress -AccountPassword (ConvertTo-SecureString "Password1" -AsPlainText -force) -enabled $true -PasswordNeverExpires $false -Passthru}
I have been over it many times I cannot see the issue in or arround on character 59
any help would be welcome
it was country that was the problem, it took a bit but I was able to comment out most of the block until I found that $_.Country did not work
Your piped variable token is wrong, it should be $_ rather than $ ie:
Import-Csv .\tableofusers.csv | foreach-object {New-ADUser -Path "ou=ou,dc=dc" -SamAccountName $_.SamAccountName -Name $_.name -DisplayName $_.name -GivenName $_.gn -SurName $_.sn -StreetAddress $_.SA -city $_.city -state $_.state -PostalCode $_.PostalCode -Country $_.Country -officephone $_.officephone -emailaddress $_.emailaddress -AccountPassword (ConvertTo-SecureString "Password1" -AsPlainText -force) -enabled $true -PasswordNeverExpires $false -Passthru}
This should do the trick.
At a guess the value given to -country in the CSV file was something like United Kingdom instead of the code for the country which is GB.
You can look up a country code by setting the country/region in AD on the address page using the drop down list. Then whilst you have Advanced Features turned on (View>Advanced Features) open the user and on the Attribute Editor tab look look for the value of attribute c to see the code for the country you've set. Put that country code into the CSV file and it should work.
In my case it was using initials with more than 6 characters. Using dots between the initials means that > 6 is already reached when the initials are "A.B.C."