Help improving AD user create script.

I am working on a script to create an active directory user and home folder. I am looking for some tips and perhaps some help changing the input so that I can put in a username in the format of LastName,FirstName. Then it would fill in the Name = First initial Lastn Name, SamAccountName = First initial LastName, GivenName = first name, Surname = last name, DisplayName = First Name Last Name , UserPrincipalName = first name last initial

import-module activedirectory
$UserN = Read-Host -Prompt 'Input the user name'
New-ADUser -name $UserN -SamAccountName $UserN -GivenName "FirstName" -Surname "LastName" -DisplayName "Whole Name"  -UserPrincipalName (“{0}@{1}” -f $UserN,””) -Path 'OU=Staff,DC=homelab,DC=com' -AccountPassword (ConvertTo-SecureString -AsPlainText "P@ssw0rd" -Force) -ChangePasswordAtLogon $true -Department "HTMB" -Description "Test Description" -EmailAddress "" -EmployeeID "123456" -Enabled $true -HomeDirectory "\\\Share\$UserN" -HomeDrive 'h:'
$Path = "\\\share\"

New-Item -type directory -path $path$UserN
$Acl = Get-Acl $path$userN
$Ar = New-Object"$UserN","FullControl","Allow")
Set-Acl "$path$userN" $Acl

Open in new window

Who is Participating?
oBdAConnect With a Mentor Commented:
With a command like New-ADUser, which requires a lot of arguments, it's best to use a splatted hash table to provide the arguments.
$Input = Read-Host -Prompt "Input the user name as 'LastName, FirstName'"
If ($Input -notmatch '\A\s*(?<LastName>\w+)\s*,\s*(?<FirstName>\w+)\s*\Z') {
	"Invalid input '$($Input)'" | Write-Error
	Exit 1
$LastName = $Matches['LastName']
$FirstName = $Matches['FirstName']

$ADUser = [ordered]@{}
$ADUser['Name'] =					"$($FirstName[0])$($LastName)"
$ADUser['SamAccountName'] =			"$($FirstName[0])$($LastName)"
$ADUser['GivenName'] =				$FirstName
$ADUser['Surname'] =				$LastName
$ADUser['DisplayName'] =			"$($FirstName) $($LastName)"
$ADUser['UserPrincipalName'] =		"$($FirstName[0])$($LastName)"
$ADUser['Path'] =					'OU=Staff,DC=homelab,DC=com'
$ADUser['AccountPassword'] =		ConvertTo-SecureString -AsPlainText 'P@ssw0rd' -Force
$ADUser['ChangePasswordAtLogon'] =	$True
$ADUser['Department'] =				'HTMB'
$ADUser['Description'] =			'Test Description'
$ADUser['EmailAddress'] =			"$($FirstName[0])$($LastName)"
$ADUser['EmployeeID'] =				'123456'
$ADUser['Enabled'] =				$True
$ADUser['HomeDirectory'] =			"\\\Share\$($ADUser['SamAccountName'])"
$ADUser['HomeDrive'] =				'H:'

"Creating a new user with the following properties:"
$ADUser.GetEnumerator() | Format-Table

New-ADUser @ADUser -WhatIf

Open in new window

RoccatAuthor Commented:
This is great, Thank you!
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.