ADuser not adding samAccountName after changing Variable - powershell

Thanks in advance !
I have made a script and in this script, I add users from excel to AD and it works for 99% but I need to make 1 change to it but when I do that it gives me errors.
Import-Csv -Path C:\Users\admin.kln\Documents\Project\BOSAN_USERS.csv |foreach{
#All strings of variables you need out of excel
$Firstname = $_.Firstname
$Lastname = $_."Last Name"
$Displayname = $_."Display Name"
$Extraname = $_."Display Name"
$Logonname = $_."Logon Name"
$Accountpassword = $_.AccountPassword
$Description = $_.Description
$Jobtitle = $_."Job Title"
$Department = $_.Department
$Company = $_.Company
$Telephonenumber = $_.TelephoneNumber
$Mobilenumber = $_."Mobile number"
$Street = $_.Street
$PObox = $_."P.O. Box"
$City = $_.City
$State = $_."State / Province"
$Zip = $_.Zip
$Country = $_.Country
$Manager = $_.Manager
$ProxyEmail = $_."Proxy Address + Email(SMTP)"
$ProxyAdress = $_."Proxy Addresss(smpt)"
$ProxySip = $_."Proxy address (SIP)"
$Final = (($_.Firstname.ToLower().Substring(0,1)) + '.' + ($_."Last name".ToLower()))
#int
$i = 1
$u = 1
$o = 1
#Check if its over 18 chars if it is it will be shortened
if ($Displayname.Length -gt 18) { $Displayname = $Displayname.Substring(0,18) }
if ($Extraname.Length -gt 18) { $Extraname = $Extraname.Substring(0,18) }
try
{
while (Get-ADUser -F {SamAccountName -eq $Extraname})
{
Write-Warning "Er bestaat al een account met de naam $Extraname"
$Extraname = $Displayname + [string]$i
$i++
$Logonname = $Logonname + [string]$o
$o++
$Final = (($_.Firstname.ToLower().Substring(0,1)) + '.' + ($_."Last Name".ToLower()))
$Final = $Final + [string]$u
$u++
}
}
catch{}
finally
{
$Logonname = $Logonname -replace ' ',''
$Final = $Final -replace ' ',''
echo $Final
New-ADUser -Path "ou=Users,ou=NLHKH,dc=CONTOSO,dc=com" `
-SamAccountName $Extraname `
-GivenName $Firstname `
-Name $Extraname `
-Surname $Lastname `
-DisplayName $Extraname `
-UserPrincipalName $Final `
-accountpassword(ConvertTo-SecureString "Password1" -AsPlainText -force) `
-ChangePasswordAtLogon $true `
-Description $Description `
-Title $Jobtitle `
-Department $Department `
-Company $Company `
-MobilePhone $Mobilenumber `
-StreetAddress $Street `
-City $City `
-State $State `
-PostalCode $Zip `
-POBOX $PObox
}
}
As you can see it should work like this but I need to change -SamAccountName to $final or at least to the same Variable as $Final. But that won't do.

Personally, I would change quite a lot of your script.
First of all, you need two loops to figure out if
you get a valid unique SamAccountName
you get a valid unique UserPrincipalName
The ProxyAddresses need extra care aswell. You need to create an array of the 3 Proxy* fields in the CSV and add that with parameter OtherAttributes.
Mind that his will not accept a 'normal' array and that it needs to be cast with [string[]] to form a strongly typed string array.
Finally, use Splatting for the New-ADUser cmdlet to get rid of those nasty backticks.
Something like this:
Import-Csv -Path 'C:\Users\admin.kln\Documents\Project\BOSAN_USERS.csv' | ForEach-Object {
# unused fields in the CSV:
# $Logonname = $_."Logon Name"
# $Country = $_.Country
# $Manager = $_.Manager
# construct a SamAccountName from the DisplayName in the CSV
# replace all invalid characters and cut off anything over 20 characters
$SamAccountName = $_."Display Name" -replace '[\x00-\x20"[\]:;|=+*?<>/,#\s]'
if ($SamAccountName.Length -gt 20) { $SamAccountName = $SamAccountName.Substring(0, 20) }
$temp = $SamAccountName
# enter an endless loop to test if that user with that SamAccountName already exists
$i = 1
while ($true) {
$user = Get-ADUser -Filter "SamAccountName -eq '$SamAccountName'" -ErrorAction SilentlyContinue
# if a user with that SamAccountName does not yet exist, we can break out of the loop
if (!$user) { break }
# create a new SamAccountName to test
while (($temp + $i).Length -gt 20) {
$temp = $temp.Substring(0, $temp.Length - 1)
}
$SamAccountName = '{0}{1}' -f $temp, $i
$i++
}
# since your UPN uses a different format than 'SamAccountName#CONTOSO.com',
# start another loop to make sure that too is unique
# CHANGE #CONTOSO.com TO THE REAL DOMAIN NAME
$UserPrincipalName = '{0}.{1}#CONTOSO.com' -f $_.Firstname.Substring(0,1).ToLower(), $_."Last name".ToLower()
$i = 1
while ($true) {
$user = Get-ADUser -Filter "UserPrincipalName -eq '$UserPrincipalName'" -ErrorAction SilentlyContinue
# if a user with that UserPrincipalName does not yet exist, we can break out of the loop
if (!$user) { break }
# create a new UserPrincipalName by adding a sequence number to test
$UserPrincipalName = '{0}.{1}{2}#CONTOSO.com' -f $_.Firstname.Substring(0,1).ToLower(), $_."Last name".ToLower(), $i
$i++
}
# next, create an array of the Proxy Addresses. Watch the spelling in the CSV headers!
$ProxyAddresses = ('SMTP:{0}' -f ($_."Proxy Address + Email(SMTP)" -replace '^SMTP:')),
('smtp:{0}' -f ($_."Proxy Address(smpt)" -replace '^smtp:')),
('SIP:{0}' -f ($_."Proxy address (SIP)" -replace '^SIP:'))
# now that we have unique names and a ProxyAddresses array, we can create the user
$NewUserParms = #{
'SamAccountName' = $SamAccountName
'Name' = ('{0} {1}' -f $_.FirstName, $_."Last Name").Trim()
'DisplayName' = $_."Display Name"
'UserPrincipalName' = $UserPrincipalName
'GivenName' = $_.FirstName
'Surname' = $_."Last Name"
'Description' = $_.Description
'Title' = $_."Job Title"
'Department' = $_.Department
'Company' = $_.Company
'AccountPassword' = ConvertTo-SecureString $_.AccountPassword -AsPlainText -Force
'ChangePasswordAtLogon' = $true
'Enabled' = $true
'OfficePhone' = $_.TelephoneNumber
'MobilePhone' = $_."Mobile number"
'StreetAddress' = $_.Street
'City' = $_.City
'State' = $_."State / Province"
'PostalCode' = $_.Zip
'POBox' = $_."P.O. Box"
'EmailAddress' = $_."Proxy Address + Email(SMTP)" -replace '^SMTP:'
'Path' = "OU=Users,OU=NLHKH,DC=CONTOSO,DC=com"
# ProxyAddresses needs cast to [string[]]
'OtherAttributes' = #{'proxyAddresses' = [string[]]$ProxyAddresses}
# add other properties to set from the CSV here if needed.
# make sure you get the parameter data types correct and always check here:
# https://learn.microsoft.com/en-us/powershell/module/addsadministration/new-aduser?view=win10-ps#parameters
# switch parameters for the cmdlet can also be entered with a value $false or $true
}
try {
# '-ErrorAction Stop' ensures that also non-terminating errors get handled in the catch block
New-ADUser #NewUserParms -ErrorAction Stop
}
catch {
# something bad happened. Change 'Write-Warning' into 'throw' if you want your script to exit here
# inside a catch block, the '$_' automatic variable represents the actual exception object.
Write-Warning "Could not create account $username. $($_.Exception.Message)"
}
}

Related

Add users in bulk with csv file

I am trying to make a script that creates users in bulk from a csv file. I tested the script with 5 users, but get the error message "New-ADUser: A value for the attribute was not in the acceptable range of values." I have been searching everywhere, but can't find the mistake!
function Get-RandomCharacters($length, $characters) {
$random = 1..$length | ForEach-Object { Get-Random -Maximum $characters.length }
$private:ofs=""
return [String]$characters[$random]
}
$ADUsers = Import-csv C:\Users\Admin\Users.csv -Delimiter ";"
foreach ($User in $ADUsers)
{
$Password = Get-RandomCharacters -length 20 -characters 'ABCDEFGHKLMNOPRSTUVWXYZabcdefghiklmnoprstuvwxyz1234567890!._?/'
$Username = $User.GivenName.substring(0,3) + $User.SurName.substring(0,3)
$Username = $Username.Replace('æ','ae')
$Username = $Username.Replace('ø','o')
$Username = $Username.Replace('å','aa')
$Username = $Username.ToLower()
$Username = $Username.Trim()
$Email = $Username + '#ONPremiumIT.com'
$DisplayName = $User.GivenName + ' ' + $User.SurName
New-ADUser `
-Path $User.Path `
-SamAccountName $Username `
-UserPrincipalName $Email `
-Name "$User.GivenName $User.SurName" `
-GivenName $User.GivenName `
-Surname $User.SurName `
-Enabled $True `
-ChangePasswordAtLogon $false `
-DisplayName "$Displayname" `
-Department $Department `
-AccountPassword (convertto-securestring $Password -AsPlainText -Force)
}
csv file:
GivenName;SurName;Department;Path
Tobias;Santelmann;it-drift;OU=it-drift,OU=onprit-brukere,DC=sec,DC=core
Maria;Aas;dev-team;OU=dev-team,OU=onprit-brukere,DC=sec,DC=core
Anniken;Arildset;renhold;OU=renhold,OU=onprit-brukere,DC=sec,DC=core
Thea;Urne;regnskap;OU=regnskap,OU=onprit-brukere,DC=sec,DC=core
Marthea;Wichstad;hr;OU=hr,OU=onprit-brukere,DC=sec,DC=core
The error comes from -Name "$User.GivenName $User.SurName", which should have been -Name "$($User.GivenName) $($User.SurName)".
Example:
"$User.GivenName $User.SurName" # --> #{GivenName=Tobias; Surname=Santelmann}.GivenName #{GivenName=Tobias; Surname=Santelmann}.SurName
but when using the Subexpression operator $(..), it does what you want:
"$($User.GivenName) $($User.SurName)" # --> Tobias Santelmann
Also, when using lots of parameters, you can have difficult to spot errors when using those backticks.
I'd suggest using Splatting for that:
$userParams = #{
Path = $User.Path
SamAccountName = $Username
UserPrincipalName = $Email
Name = '{0} {1}' -f $User.GivenName, $User.SurName # or: "$($User.GivenName) $($User.SurName)"
GivenName = $User.GivenName
Surname = $User.SurName
Enabled = $true
ChangePasswordAtLogon = $false
DisplayName = $Displayname
Department = $Department
AccountPassword = (ConvertTo-SecureString $Password -AsPlainText -Force)
}
New-ADUser #userParams

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'

Add a command at the end of the PowerShell script

I have a script that adds user to Active Directory
Import-Module activedirectory
$ADUsers = Import-csv E:\src\userlist.csv
foreach ($User in $ADUsers)
{
$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
$postalcode = $User.postalcode
$state = $User.state
$country = $User.country
$telephone = $User.telephone
$jobtitle = $User.jobtitle
$company = $User.company
$department = $User.department
$Password = $User.Password
# check if user already existe
if (Get-ADUser -F {SamAccountName -eq $Username})
{
Write-Warning "The $Username already exist."
}
else
{
#create user account in the good $OU from the csv
New-ADUser -SamAccountName $Username -UserPrincipalName "$Username#" -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 -postalcode $postalcode -AccountPassword (convertto-securestring $Password -AsPlainText -Force) -ChangePasswordAtLogon $false
}
}
In the same script, I want also to have the New-ADUser command that will add the proxy address mail as below:
Set-ADUser -Identity $Username -EmailAddress $email -add {ProxyAddresses="smtp:$email"}
How can I add New-ADUser to my script?
To avoid having to create so many variables from the CSV first and mainly to not having to use the backticks in your code, I would suggest you switch to using Splatting to make the code more readable and maintainable.
You can add the proxyAddresses attribute with the New-ADUSer cmdlet using the OtherAttributes parameter, OR use Set-ADUser to add this after creating the user.
The proxyAddresses attribute is an array of strongly typed strings. That means you cannot use a 'normal' array (Object[]), because in there you can have all kind of value types, not just strings. This is why the code below casts the SMTP email address to [string[]].
I'm assuming the email address to add should be the Primary email address, so that is why I use SMTP: (all caps).
Import-Csv -Path 'E:\src\userlist.csv' | ForEach-Object {
# the '$_' automatic variable holds one record from the CSV
# for convenience create these two variables
$accountName = $_.username
# the proxyAddresses attribute is an array of STRONGLY typed strings
$proxyAddresses = [string[]]"SMTP:$($_.email)"
# check if user already exists
if (Get-ADUser -Filter "SamAccountName -eq '$accountName'") {
Write-Warning "The $accountName already exist."
}
else {
# lire les variables de chaque champs et les assigner en variables de commandes
# use Splatting
$userParams = #{
SamAccountName = $accountName
UserPrincipalName = "$accountName#yourdomain.com"
Name = '{0} {1}' -f $_.firstname, $_.lastname
DisplayName = '{0}, {1}' -f $_.lastname, $_.firstname
GivenName = $_.firstname
Surname = $_.lastname
Enabled = $true
Path = $_.ou
City = $_.city
Company = $_.company
State = $_.state
StreetAddress = $_.streetaddress
OfficePhone = $_.telephone
EmailAddress = $_.email
Title = $_.jobtitle
Department = $_.department
PostalCode = $_.postalcode
AccountPassword = (ConvertTo-SecureString $_.Password -AsPlainText -Force)
ChangePasswordAtLogon = $false
# either add the proxyAddresses here, or do it AFTER creating the new user with
# Set-ADUser -Identity $accountName -Add #{'proxyAddresses' = $proxyAddresses}
OtherAttributes = #{'proxyAddresses' = $proxyAddresses}
}
#create user account in the good $OU from the csv
New-ADUser #userParams
}
}
Hope this helps

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
}

Add Multiple Users To AD, CSV

I'm attempting to import users via a CSV folder.
I have certain parameters that need to be kept, so I'm only using certain fields.
Powershell
$csv = Import-Csv -Path "newusers.csv"
foreach ($User in $csv)
{
#region Data Generation
$DisplayName = $User.'Surname' + " " + $User.'GivenName'
$Mail = $User.'GivenName' + "." + $User.'Surname' + "#" + "royalberkshire.nhs.uk"
$MailAlias = $User.'GivenName' + "." + $User.'Surname' + "#" + $DNSRoot2
$SInitial = $User.'Surname'[0]
$Initial = $User.'GivenName'[0]
$SAMAccountName = $User.'Surname' + "" + $Initial
$SAMAccountLower = $SAMAccountName.ToLower()
$UserPrincipalName = $User.'Surname'+$Initial
$HD = "U"
$HDir = "\\RBHFILRED002\"
$AC = "Users_01$\"
$DH = "Users_02$\"
$IM = "Users_03$\"
$NS = "Users_04$\"
$TZ = "Users_05$\"
$Folder = if ($SInitial -in 'a','b','c'){$AC}
ElseIf ($SInitial -in 'd','e','f', 'g','h'){$DH}
ElseIf ($SInitial -in 'i','j','k', 'l','m'){$IM}
ElseIf ($SInitial -in 'n','o','p', 'q','r','s'){$NS}
Else {$TZ}
$group1 = "zz Everyone"
$group2 = "Safeboot Domain Users"
$defaultname = $SAMAccountName
$email = $User.'GivenName' + "." + $User.'Surname'
$i = 1
cls
# Create The User
While ((Get-ADUser -Filter "SamAccountName -eq '$SAMAccountName'" -ErrorAction SilentlyContinue) -ne $null){
$SamAccountName = $defaultname + [string]$i
$Mail = $email + [string]$i + "#" + "royalberkshire.nhs.uk"
$i++
}
$NewUserParams = #{
path = "OU=Users,OU=RBFT,DC=rbbh-tr,DC=nhs,DC=uk"
SamAccountName = $SAMAccountName
Name = $SAMAccountName
DisplayName = $DisplayName
GivenName = $User.'GivenName'
Surname = $User.'Surname'
EmailAddress = $Mail
UserPrincipalName = "$SAMAccountName#rbbh-tr.nhs.uk"
Title = $title
HomeDrive = $HomeDrive
HomeDirectory = "$HDir$Folder$SAMAccountName"
Description = $User.'Description'
ChangePasswordAtLogon = $true
PasswordNeverExpires = $false
AccountPassword = $password
Enabled = $true
}
New-ADUser #NewUserParams -ErrorAction SilentlyContinue
Add-ADGroupMember -Identity $group1 -Members $SAMAccountName
Start-Sleep -s 10
Add-ADGroupMember -Identity $group2 -Members $SAMAccountName
cls
echo "Please Wait Whilst We Create The AD Account & Create The Exchange Mailbox.."
Start-Sleep -s 30
Enable-Mailbox -Identity $SAMAccountName
cls
echo "Please Wait Whilst We Activate The Exchange Mailbox..."
Start-Sleep -s 15
# Sets The User Up With The Randomised Password, And Re-Encrypts It For Double Protection
Set-ADAccountPassword -Identity $SAMAccountName -Reset -NewPassword (ConvertTo-SecureString -AsPlainText $random -Force)
cls
}
CSV
User GivenName Surname Description
User James Timms Test
User James Timms Test
User Hulk Hogan Test
User Ultimate Warrior Test
User The Rock Test
User Dwayne Johnson Test
The script does not run. It tells me that the Search Filter Cannot Be Recognized.
It just errors on me.
It works with a single user fine using Write-Hosts and Inputs.
However with the CSV it doesn't work.
I must note, this is also the first time I've created users via a CSV on powershell.
Does anybody have any idea on how to fix this issue?
I got it working,
Turns out when I was building the CSV within Excel 2016 it wasn't adding the commas to seperate values.
I ended up opening the CSV within notepad and added commas to separate the values.
Powershell reads the Values based on Comma Seperation, so if there are no commas, it doesn't know what values to push out.