I am working on a script creating a new user via PowerShell with user (creator) input. The input I am looking for is for the first name and last name along with some attributes. I would like the samaccountname and the UPN to be auto created from the input. Not sure if this can be done completely but would like to get some input on my current script. I highlighted firstinital as a placeholder to show what I am trying to accomplish.
new-aduser -givenname($givenname = read-host "Input Firstname") -surname($surname = read-host "Input Lastname") -samAccountName ("***firstinitial***"+"$._surname") -userprincipalname "$._surname+"#domain.com" -path "OUName" -whatif
Alrighty thanks for the help below. I was able to do a few more searches and can up with the following. All looks to work except the distingushed name comes up as a single name instead of a space between the first and last name.
#User info entered
$first = Read-Host "First name"
$last = Read-Host "Last name"
$title = Read-Host "Title"
$location = Read-Host "Location"
$department = Read-Host "Business Practice"
$password = read-host -assecurestring "Password"
#Create new user
$Attributes = #{
Enabled = $true
ChangePasswordAtLogon = $false
UserPrincipalName = $first.split(" ")[0]+$last+"#domain.com"
Name = $first+$last
GivenName = $first
Surname = $last
DisplayName = "$first "+" $last"
Office = $location
Department = $department
Title = $title
samAccountName = $first.split(" ")[0] + $last
AccountPassword = $password
}
New-ADUser #Attributes -whatif
You can add this to get the $_.givenName as the first initial:
$gn = (read-host "Input Firstname")
$sn = (read-host "Input Lastname")
new-aduser -givenname $gn -surname $sn -samAccountName $gn.split(" ")[0]+$sn -userprincipalname $sn+"#kfriese.com" -path "OUName" -whatif
Here is a more advanced and robust way to do it: a custom function, that makes use of PowerShell integrated functionality.
It uses attributes that make the parameters mandatory, so user input will automatically be inquired when the function is called. Also a validation attribute to make sure the input is not empty and has no invalid characters (you might want to adjust the regex according to your needs).
The arguments for New-ADUser are passed using splatting. The rest is pretty straight-forward...
function makeuser {
param(
[Parameter(Mandatory, Position = 0)]
[ValidatePattern("[a-z]+")]
[string]$GivenName,
[Parameter(Mandatory, Position = 1)]
[ValidatePattern("[a-z]+")]
[string]$Surname
)
$params = #{
GivenName = $GivenName
Surname = $Surname
SamAccountName = $GivenName[0] + $Surname
UserPrincipalName = $Surname + "#kfriese.com"
Path = "OUName"
}
New-AdUser #params
}
To call the function, just type (parameter values will be inquired automatically)
makeuser
Or specify the values explicitly:
makeuser -GivenName Foo -Surname Bar
# or
makeuser foo bar
I tried to automate creating AD users in my lab environment and came across an interesting issue that I cannot seem to grasp. When I tried using the following code, Powershell threw "New-ADUser : The name provided is not a properly formed account name"
$Attributes = #{
Enabled = $true
ChangePasswordAtLogon = $false
Departent = "MyDepartment"
UserPrincipalNAme = "first.name#domain.lel"
City = "MySite"
DisplayName = "My display name"
EmailAddress = "My#mail.address"
GivenName = "First Name"
Manager = "cbu"
PasswordNeverExpires = $true
SamAccountName = "abc123"
Surname = "Last name"
Title = "Title"
Name = "abc123"
AccountPassword = $("Thishere1234" | ConvertTo-SecureString -AsPlainText -Force)
}
New-ADUser $Attributes
The above example is close to a copy paste from some post that I found using hashtables as a way to pass the information to New-ADUser. Since this did not work, I instead tried the following:
$Attributes = [pscustomobject]#{
Enabled = $true
ChangePasswordAtLogon = $false
Departent = "MyDepartment"
UserPrincipalNAme = "first.name#domain.lel"
City = "MySite"
DisplayName = "My display name"
EmailAddress = "My#mail.address"
GivenName = "First Name"
Manager = "cbu"
PasswordNeverExpires = $true
SamAccountName = "abc123"
Surname = "Last name"
Title = "Title"
Name = "abc123"
AccountPassword = $("Thishere1234" | ConvertTo-SecureString -AsPlainText -Force)
}
$Attributes | New-ADUser
This works just fine. My question is: why would the first hashtable approach not accept the name property but the second PSCustomObject does accept the exact same approach?
As a bonus question, is there any particular reason I cannot use New-ADUser $Attributes but rather I have to pipe $Attributes to New-ADUser? I was under the impression you could use the former too?
When splatting using a hashtable, you need to use the # sign on the cmdlet, not a $:
New-ADUser #Attributes
I'm trying to create a new AD user through a script. Unfortunately there are several unusual attributes of the account I need to set. I tried to use the -OtherAttributes parameter, but it didn't work, Powershell said they are unknown parameters. I'm talking about these attributes:
Anyone knows how to set these parameters?
Have you tried it with Set-AdUser?
Set-ADUser $Name –replace #{extensionAttribute5="Company"}
or with a hash table
$Attributes = #{
Name = "Test User"
SamAccountName = "Testuser"
Enabled = $true
Path = "OU=Users,DC=Domain,DC=local"
AccountPassword = "1234567"
ChangePasswordAtLogon = $False
GivenName = "Test"
EmployeeID = "1234"
Surname = "Test User"
DisplayName = "Test User"
Initials = "TU"
Description = "Test User for tests"
UserPrincipalName = "Test#domain.local"
Office = "Test Office"
Company = "Test Company"
Department = "Test Department"
Division = "Test Division"
EmailAddress = "test#test.local"
OtherAttributes = #{
extensionAttribute4 = "Test Data"
extensionAttribute5 = "Test Data"
}
}
New-ADUser #Attributes -PassThru
I stopped over at Code Review, asking how I could streamline a script and was advised to use a hashtable as it would clean up the code. I was given a very basic example but it wasn't plug-and-play. I've worked up some basic code but it's not doing what I think it should. Knowing the Code Review folks aren't there for support like this, here i am, looking for help with combining a variable from a CSV and a hashtable. I'll leave sample data from my CSV and the Powershell code below.
Sample CSV:
Student First Name,I,Student Last Name,Other ID,Stu Access Login,Student's School Email,School,Grad Year
Johosofat,L,Smith,999999,smithjoh000,smithjoh000#mydomain.org,30,2017
Tome,M,Smith,999998,smithtom000,smithtom000#mydomain.org,40,2021
Sample Powershell:
# Testing simple hash table
$SchoolCodes = #{
20 = "Exeter Township Senior High"
30 = "Exeter Township Junior High"
40 = "Lorane Elementary School"
50 = "Jacksonwald ES"
70 = "Reiffton School"
90 = "Owatin Creek Elementary School"
}
# CSV file being imported.
$CsvFile = "$env:USERPROFILE\Downloads\SampleData.csv"
# Import the contents of the CSV file.
$Users = Import-Csv -Path "$CsvFile"
# Loop through each line of the CSV, creating variables for each field.
ForEach ($User in $Users) {
# Creating the basic variables.
$FirstName = $User.'Student First Name'
$MiddleInitial = $User.'I'
$LastName = $User.'Student Last Name'
$ADUserName = $User.'Stu Access Login'
$StudentID = $User.'Other ID'
$GradYear = $User.'Grad Year'
$CapFInitial = $FirstName.substring(0,1).ToUpper()
$MInitial = $MiddleInitial.substring(0,1).ToLower()
$LInitial = $LastName.substring(0,1).ToLower()
$Password = "$CapFInitial$MInitial$LInitial" + "#" + "$StudentID"
$SchoolCode = $SchoolCodes[$User.School]
If (-Not(Get-ADUser -Filter {SamAccountName -eq $ADUserName})) {
Try {
# Create user.
New-ADUser `
-Name "$FirstName $LastName" `
-SamAccountName "$ADUserName" `
-GivenName "$FirstName" `
-Initials "$MiddleInitial" `
-Surname "$LastName" `
-DisplayName "$FirstName $MiddleInitial. $LastName" `
-UserPrincipalName "$ADUserName#mydomain.k12.pa.us" `
-EmailAddress "$ADUserName#mydomain.k12.pa.us" `
-AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) `
-Enabled $false `
-PasswordNeverExpires $true `
-CannotChangePassword $true `
-Path "OU=$GradYear,OU=Students,OU=$SchoolCode,OU=accounts,DC=academic,DC=mydomain,DC=k12,DC=pa,DC=us" `
-WhatIf
}
Catch {
Write-Error "[ERROR] Can't create user [$($ADUserName)] : $_"
}
}
}
My issue:
The script ultimately errors out because of the $SchoolCode variable being set to null, I think. I'm wanting the script to find the number (code) from the school field in the CSV and match that to the name which ends up being an OU in AD - where the User Object will get created. Basically, the code tries to create the User Object in "CN=Tome Smith,OU=2021,OU=Students,OU=,OU=accounts,DC=academic,DC=exeter,DC=k12,DC=pa,DC=us" which shows the $SchoolCode variable is either blank or otherwise not getting set correctly.
As I mentioned in a comment, we're thinking of adding other static data to the hashtable as a (nested?) hashtable. Here's an example of what we're thinking about. As time goes by, the list of AD groups may grow.
Example of the nested hashtable:
$SchoolCodes = #{
20 = #{
Name = "Exeter Township Senior High"
ADGroup1 = "Students"
ADGroup2 = "Secondary Students"
}
30 = #{
Name = "Exeter Township Junior High"
ADGroup1 = "Students"
ADGroup2 = "Secondary Students"
}
40 = #{
Name = "Lorane Elementary School"
ADGroup1 = "Students"
ADGroup2 = "K4 Students"
}
50 = #{
Name = "Jacksonwald ES"
ADGroup1 = "Students"
ADGroup2 = "K4 Students"
}
70 = #{
Name = "Reiffton School"
ADGroup1 = "Students"
ADGroup2 = "Secondary Students"
}
90 = #{
Name = "Owatin Creek Elementary School"
ADGroup1 = "Students"
ADGroup2 = "K4 Students"
}
}
I'm scouring the web and trying to get a better understanding of hashtables. If I can wrap my head around it, nesting them would be my next step.
Unless you're re-using the data, it's not important to turn it into a hashtable. Also, the error is in accessing the $SchoolCodes value. For some reason, the accessor isn't working with a [String], but does work when you cast to an [Int]
Sample dataset:
Student First Name,I,Student Last Name,Other ID,Stu Access Login,Student's School Email,School,Grad Year
Johosofat,L,Smith,999999,smithjoh000,smithjoh000#mydomain.org,30,2017
Tome,M,Smith,999998,smithtom000,smithtom000#mydomain.org,40,2021
Code:
#requires -Version 3
$SchoolCodes = #{
20 = "Exeter Township Senior High"
30 = "Exeter Township Junior High"
40 = "Lorane Elementary School"
50 = "Jacksonwald ES"
70 = "Reiffton School"
90 = "Owatin Creek Elementary School"
}
# CSV file being imported.
$CsvFile = "$env:USERPROFILE\Downloads\SampleData.csv"
# Import the contents of the CSV file.
$Users = Import-Csv -Path "$CsvFile"
# Loop through each line of the CSV, creating variables for each field.
ForEach ($User in $Users)
{
[String]$LoginName = $User.'Stu Access Login'
If (-not (Get-ADUser -Filter {SamAccountName -eq $LoginName}))
{
$FirstName = $User.'Student First Name'
$LastName = $User.'Student Last Name'
$Params = #{
Name = "$FirstName $LastName"
SamAccountName = $LoginName
GivenName = $FirstName
Initials = $User.I
Surname = $LastName
DisplayName = "$FirstName $($User.I) $LastName"
UserPrincipalName = "$LoginName#mydomain.k12.pa.us"
EmailAddress = "$LoginName#mydomain.k12.pa.us"
AccountPassword = ConvertTo-SecureString -String (
'{0}{1}{2}#{3}' -f #(
$FirstName[0].ToString().ToUpper(),
$User.I[0].ToString().ToLower(),
$LastName[0].ToString().ToLower(),
$User.'Other ID')) -AsPlainText -Force
Enabled = $False
PasswordNeverExpires = $True
CannotChangePassword = $True
Path = 'OU={0},OU=Students,OU={1},OU=accounts,DC=academic,DC=mydomain,DC=k12,DC=pa,DC=us' -f #(
$User.'Grad Year',
$SchoolCodes[[Int]$User.School])
WhatIf = $True
}
Try {New-ADUser #Params}
Catch {Write-Error "[ERROR] Can't create user [$LoginName] : $_"}
}
}
Why does my loop only happen once? I want to enter 5 users and add it to a hashtable, but the code runs once then stops. How Do I fix it?
$userID=""
$firstname=""
$lastname="
$personCount = 1
$personHash = #{}
while ($personCount -le 5){
$personCount++
While([string]::IsNullOrWhiteSpace($userID)){
$userID = Read-Host "Enter ID"
}
While([string]::IsNullOrWhiteSpace($firstname)){
$firstname = Read-Host "Enter First Name"
}
While([string]::IsNullOrWhiteSpace($lastname)){
$lastname = Read-Host "Enter Last Name"
}
$user = New-Object PSCustomObject -Property #{
ID = $userID
FirstName = $firstname
LastName = $lastname
}
$personHash.Add($user.ID,$user)
}
}
Output:
Enter ID: 1001
Enter First Name: Charles
Enter Last Name: Whitfield
Name Value
---- -----
1001 #{ID=1001; FirstName=Charles; LastName=Whitfield}
1001 #{ID=1001; FirstName=Charles; LastName=Whitfield}
1001 #{ID=1001; FirstName=Charles; LastName=Whitfield}
1001 #{ID=1001; FirstName=Charles; LastName=Whitfield}
Your loop runs 5 times.
The problem is that once the variables are populated in the first loop, they fail the While condition in the all the subsequent loops. It runs one time, doing a read-host and setting the variables. Then it runs 4 more times, but doesn't find anything to do.
Your updated code is closer. You save the data, but didn't clear the variables for the next loop.
$userID=""
$firstname=""
$lastname=""
$personCount = 1
$personHash = #{}
while ($personCount -le 5){
$personCount++
While([string]::IsNullOrWhiteSpace($userID)){
$userID = Read-Host "Enter ID"
}
While([string]::IsNullOrWhiteSpace($firstname)){
$firstname = Read-Host "Enter First Name"
}
While([string]::IsNullOrWhiteSpace($lastname)){
$lastname = Read-Host "Enter Last Name"
}
$user = New-Object PSCustomObject -Property #{
ID = $userID
FirstName = $firstname
LastName = $lastname}
$personHash.Add($user.ID,$user)
$UserID,$firstname,$lastname = ""
}
Couple of issues here, the while loops need clear variables like mjolinor said. Once that is done, I suggest saving that data in an array, so the data of each user is not lost by the next iteration:
$users = #()
$personCount = 1
while ($personCount -le 5){
$userID=""
$firstname=""
$lastname=""
$personCount++
While([string]::IsNullOrWhiteSpace($userID)){
$userID = Read-Host "Enter ID"
}
While([string]::IsNullOrWhiteSpace($firstname)){
$firstname = Read-Host "Enter First Name"
}
While([string]::IsNullOrWhiteSpace($lastname)){
$lastname = Read-Host "Enter Last Name"
}
$users += New-Object -TypeName PSCustomObject -Property #{
userID = $userID;
firstName = $firstname;
lastName = $lastname
}
}
Once the array $users has all the data, you can output all the values at once with $users or specific users with $users[0],$users[1], etc.
It's clearly not possible that the code you posted would create the output you posted. Even if I discount the two syntax errors you'd still be getting 4 key conflict exceptions, because you're trying to add the same key to the same hashtable 5 times (a key in a hashtable must be unique).
If you want to create 5 user objects in a hashtable and make sure that the user enters a value for all 3 properties you could do something like this if you want a duplicate ID to throw an error:
$personHash = #{}
1..5 | % {
do {
$userID = Read-Host "Enter ID"
$firstname = Read-Host "Enter First Name"
$lastname = Read-Host "Enter Last Name"
} until ( $userID -and $firstname -and $lastname )
$user = New-Object -Type PSCustomObject -Property #{
'ID' = $userID
'FirstName' = $firstname
'LastName' = $lastname
}
$personHash.Add($userID, $user)
}
or like this if you want a duplicate ID to update the current values:
$personHash = #{}
1..5 | % {
do {
$userID = Read-Host "Enter ID"
$firstname = Read-Host "Enter First Name"
$lastname = Read-Host "Enter Last Name"
} until ( $userID -and $firstname -and $lastname )
$user = New-Object -Type PSCustomObject -Property #{
'ID' = $userID
'FirstName' = $firstname
'LastName' = $lastname
}
$personHash[$userID] = $user
}