Individual passwords for AD user | Import via CSV - powershell

I am trying to import users to AD via CSV / PowerShell.
The import now works fine, the users and all attributes are correct, but it seems like the passwords are not imported correctly from my .csv.
Here is my .ps1 im using:
#Import required modules
Import-Module ActiveDirectory
#Prompt user for CSV file path
$filepath = Read-Host -Prompt "Enter Path of CSV"
$securePassword = ConvertTo-SecureString $pass -AsPlainText -Force
# Import the file into a variable
$users = Import-Csv $filepath -Delimiter ";"
#Loop through each row and gather information
ForEach ($user in $users) {
#Gather the user's information
$fname = $user.FirstName
$lname = $user.LastName
$uname = $user.Username
$email = $user.Email
$jtitle = $user.Title
$OUpath = $user.'Organizational Unit'
$pass = $user.Password
$SAM = $user.SAM
#Create new AD user for each user in CSV file
New-ADUser -Name "$fname $lname" -GivenName $fname -Surname $lname -UserPrincipalName $uname -SamAccountName $SAM -Path $OUpath -AccountPassword $securePassword -PasswordNeverExpires $true -Enabled $true -EmailAddress $email
# Echo for every user created
}
Does anybody have a clue what the reason could be here?
Thanks,
Marius

You are converting $pass to secure string before it is imported from the csv. So the fixed one:
#Import required modules
Import-Module ActiveDirectory
#Prompt user for CSV file path
$filepath = Read-Host -Prompt "Enter Path of CSV"
# Import the file into a variable
$users = Import-Csv $filepath -Delimiter ";"
#Loop through each row and gather information
ForEach ($user in $users) {
#Gather the user's information
$fname = $user.FirstName
$lname = $user.LastName
$uname = $user.Username
$email = $user.Email
$jtitle = $user.Title
$OUpath = $user.'Organizational Unit'
$pass = $user.Password
$SAM = $user.SAM
$securePassword = ConvertTo-SecureString $pass -AsPlainText -Force
# The Rest

Related

If AD account exists, append a counter to the username started at 2

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++
}

Directory Object Not Found - Active Directory - Inputting from CSV

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

Powershell Active Directory username

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'

New-ADUser OtherAttributes var from CSV

I'm using the powershell script below to create new AD accounts from a CSV file. I recently added the vars for $extensionAttribute1 and $extensionAttribute2. I also added the following -OtherAttributes = #{'extensionAttribute1' = $extensionAttribute1;'extensionAttribute2'= $extensionAttribute2}
How can I correct for the following error?
New-ADUser : Cannot validate argument on parameter 'OtherAttributes'. The argument is null or an element of the argument collection contains a null value. At D:\OneDrive\Element Care\Powershell\SACRequest - Create Accounts via CSV.ps1:62 char:30 + ... -OtherAttributes #{'extensionAttribute1' = $extensionAttribute1}
ps script is as follows:
# Import active directory module for running AD cmdlets
Import-Module activedirectory
#Store the data from ADUsers.csv in the $ADUsers variable
$ADUsers = Import-csv "\\server\path\file.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.'First Name:'
$Lastname = $User.'Last Name:'
$OU = 'OU=CONTRACTORS,OU=ACCOUNTS,OU=organization,DC=domain,DC=lan'
$Descritpion = $User.'Account Type'
$company = $User.'Employer:'
$extensionAttribute1 = $User."Submitter Name" # The employee who originally submitted the request.
$extensionAttribute2 = $User."Submitter email" # The email for who originally submitted the request.
# $email = $User.email
# $streetaddress = $User.streetaddress
# $city = $User.city
# $zipcode = $User.zipcode
# $state = $User.state
# $country = $User.country
# $telephone = $User.telephone
# $jobtitle = $User.jobtitle
# $department = $User.department
#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#domain.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 `
-Description $Descritpion `
-AccountPassword (convertto-securestring $Password -AsPlainText -Force) -ChangePasswordAtLogon $True `
-OtherAttributes #{'extensionAttribute1' = $extensionAttribute1;'extensionAttribute2'= $extensionAttribute2}
}
}
The error you recieved came IMO from the typo's you have made in the original code. Apart from that, I would advice you to use Splatting for cmdlets like New-ADUser that can have a lot of parameters. That way you keep the code both readable and maintainable, and you don't need to use the easily overlooked backtick character for line continuation.
Provided your CSV contains all of the values and all column headers are as shown in your code, something like this should work:
# Import active directory module for running AD cmdlets
Import-Module ActiveDirectory
#Store the data from ADUsers.csv in the $ADUsers variable
Import-csv "\\server\path\file.csv" | ForEach-Object {
#Check to see if the user already exists in AD
if ((Get-ADUser -Filter "SamAccountName -eq '$($_.username)'" -ErrorAction SilentlyContinue)) {
#If user does exist, give a warning
Write-Warning "A user account with username $($_.username) already exist in Active Directory."
continue
}
# only store these in variables as they are used in multiple properties
$firstName = $_.'First Name:'
$lastName = $_.'Last Name:'
# create a Hashtable with all properties you want to set for the new user
$properties = #{
'SamAccountName' = $_.username
'UserPrincipalName' = '{0}#domain.com' -f $_.username
'Name' = '{0} {1}' -f $firstName, $lastName
'GivenName' = $firstName
'Surname' = $lastName
'Enabled' = $true
'DisplayName' = '{0}, {1}' -f $lastName, $firstName
'Path' = 'OU=CONTRACTORS,OU=ACCOUNTS,OU=organization,DC=domain,DC=lan'
'City' = $_.city
'Company' = $_.'Employer:'
'State' = $_.state
'StreetAddress' = $_.streetaddress
'OfficePhone' = $_.telephone
'EmailAddress' = $_.email
'Title' = $_.jobtitle
'Department' = $_.department
'Description' = $_.'Account Type'
'AccountPassword' = (ConvertTo-SecureString $_.password -AsPlainText -Force)
'ChangePasswordAtLogon' = $true
'OtherAttributes' = #{'extensionAttribute1' = $_.'Submitter Name';'extensionAttribute2'= $_.'Submitter email'}
# you can comment out any properties you do not need or are missing in the CSV
# 'PostalCode' = $_.zipcode
# 'Country' = $_.country
}
# create the new user using the properties Hashtable (splat)
Write-Host "Creating user $($_.username)"
New-ADUser #properties
}

Adding new users to Active Directory and allowing for a cell with multiple values to be split to add individual groups to users

I have a script that creates a new user in the Active Directory. I want to be able to include a groups value into my csv template and have these split into individual values to be added with the user.
I currently run a second script to assign groups to users by outlining the group name.
# 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:\upload\batman.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
$Password = $User.Password
$groups = $User.groups
#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#lon.deloitterisk.cloud" `
-Name "$Firstname $Lastname" `
-GivenName $Firstname `
-Surname $Lastname `
-Enabled $True `
-DisplayName "$Lastname, $Firstname" `
-Path $OU `
-AccountPassword (convertto-securestring $Password -AsPlainText -
Force) -ChangePasswordAtLogon $False -PasswordNeverExpires:$True `
-group
{
foreach($groups in $ADUsers)
{
$Username = $User.username
$groups = $User.groups -split ","
foreach ($group in $groups)
}
}
}
}
This is the code that I currently have (I have added in the groups clause I am trying to add in however this section is producing errors. The column name in my template is "groups")
Disclaimer: This is untested
I would utilize what you already have and add in the Add-ADPrincipalGroupMembership command. I changed some of the formatting to use splatting with the New-ADUser command for readability purposes only.
# 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:\upload\batman.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
$NewUser = #{
'SamAccountName' = $User.username
'UserPrincipalName' = "{0}#domain.com" -f $User.username
'Name' = "{0} {1}" -f $user.firstname,$user.lastname
'Enabled' = $true
'DisplayName' = "{1}, {0}" -f $user.firstname,$user.lastname
'AccountPassword' = ConvertTo-SecureString $User.password -AsPlainText -Force
'ChangePasswordAtLogon' = $false
'PasswordNeverExpires' = $true
'GivenName' = $User.firstname
'Surname' = $User.lastname
'Path' = $User.ou #This field refers to the OU the user account is to be created in
'Password' = $User.Password
}
$groups = $User.groups -split ","
$email = $User.email
#Check to see if the user already exists in AD
if (Get-ADUser -Filter "SamAccountName -eq '$($NewUser.SamAccountName)'")
{
#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 #NewUser
Add-ADPrincipalGroupMembership -Identity $NewUser.SamAccountName -MemberOf $groups
}
}