I have a simple script that I use to create new AD users. The basic script works great and gets me to where I need to be when I create a new user. There is one part that is missing that I would like to have automated so that I wont have to update the info manually. I need to add the address and phone number for a user based on their location. From the code below, I added the if elseif statement. What I have below gives the error - The term 'Austin' is not recognized as the name of a cmdlet, function, script file, or operable program. Obviously the variable $location doesn't work with the script, however, I am not as familar with PowerShell to see where to correct this or if there should be better way to write this out. Should I add Get-ADUser in front of it to pull the user info once its been added? Or add the if, elseif at the end of the script?
#Prompt for user information
$first = Read-Host "First name"
$last = Read-Host "Last name"
$title = Read-Host "Title"
$location = Read-Host "Location (location1,location2)"
$department = Read-Host "Business Practice"
$password = read-host -assecurestring "Password"
if($location = location1) {
Set-ADUser -street "StreetName" -city "City" -state "State" -postalcode "Zip" -officephone "Phone"
}
elseif($location = location2) {
Set-ADUser -street "StreetName" -city "City" -state "State" -postalcode "Zip" -officephone "Phone"
}
#Create new user
$Attributes = #{
Enabled = $true
ChangePasswordAtLogon = $false
UserPrincipalName = $first.substring(0,1)+$last+"#domain.com"
Name = $first + " " + $last
GivenName = $first
Surname = $last
DisplayName = $first + " " + $last
Office = $location
Department = $department
Title = $title
samAccountName = $first.substring(0,1)+$last
emailaddress = $first.substring(0,1)+$last+"#domain.com"
AccountPassword = $password
Path = "OU Path"
}
New-ADUser #Attributes
Set-ADUser needs to know the user for which these properties need to be set through its Identity parameter which is missing
You can simply add these properties to the $Attributes hashtable you use for the New-ADUser cmdlet.
You just need to define some logic as to where these properties come from.
Something like using a switch:
# with '$location' just ask for the city:
$location = Read-Host "City"
# I'm making this up of course
switch ($location) {
'Austin' {
$city = 'Austin'
$state = 'Texas'
$postalcode = '73301'
$officephone = '555-123456'
break
}
'Salt Lake City' {
$city = 'Salt Lake City'
$state = 'Utah'
$postalcode = '84044'
$officephone = '555-654321'
break
}
default { $city = $null }
}
if ($city) {
$Attributes = #{
Enabled = $true
ChangePasswordAtLogon = $false
UserPrincipalName = $first.substring(0,1)+$last+"#domain.com"
Name = $first + " " + $last
GivenName = $first
Surname = $last
DisplayName = $first + " " + $last
Office = $location
Department = $department
Title = $title
samAccountName = $first.substring(0,1)+$last
emailaddress = $first.substring(0,1)+$last+"#domain.com"
AccountPassword = $password
Path = "OU Path"
# these are from the switch() above
City = $city
State = $state
PostalCode = $postalcode
OfficePhone = $officephone
}
New-ADUser #Attributes
}
Or you can create a CSV file like
City,State,PostalCode,OfficePhone
Austin,Texas,73301,555-123456
Salt Lake City,Utah,84044,555-654321
and read that using
$locations = Import-Csv -Path '<PathToTheLocations.csv>'
# with '$location' just ask for the city:
$location = Read-Host "City"
# then get the address info from there based on the given city
$address = $locations | Where-Object { $_.City -eq $location }
if ($address) {
$Attributes = #{
Enabled = $true
ChangePasswordAtLogon = $false
UserPrincipalName = $first.substring(0,1)+$last+"#domain.com"
Name = $first + " " + $last
GivenName = $first
Surname = $last
DisplayName = $first + " " + $last
Office = $location
Department = $department
Title = $title
samAccountName = $first.substring(0,1)+$last
emailaddress = $first.substring(0,1)+$last+"#domain.com"
AccountPassword = $password
Path = "OU Path"
# these are from the CSV
City = $address.City
State = $address.State
PostalCode = $address.PostalCode
OfficePhone = $address.OfficePhone
}
New-ADUser #Attributes
}
Of course, NEVER trust user input from Read-Host and build in some validation checks before creating a new user
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
Currently I have this script as test:
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName(“System.Web”) | Out-Null
$User = 'usernamehere'
$Pass = ConvertTo-SecureString 'passwordhere' -AsPlainText -Force
$SPOUrl = "sharepointlisthere"
$SPOList = "Add2AD"
$SPListItemColumns = #{
FirstName = "Title"
LastName = "Achternaam"
Title = "Functie"
Managerf = "Teamleider"
Status = "Status"
Mail = "Mail"
Laptop = "Laptop"
Accountnaam = "Accountnaam"
}
#Connect to SharePoint Online
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SPOUrl)
$Context.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User, $Pass)
#Get the list
$List = $Context.Web.Lists.GetByTitle($SPOList)
$Query = [Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery(100)
$Items = $List.GetItems($Query)
$Context.Load($Items)
$Context.ExecuteQuery()
foreach($item in $Items)
{
#Get list item for later reference
$ListItem = [Microsoft.SharePoint.Client.ListItem]$listItem = $List.GetItemById($Item.FieldValues["ID"])
if ($item.FieldValues[$SPListItemColumns.Status] -eq "Nee") {
Write-Verbose "Processing list item $Firstname $LastName with ID=$($item.FieldValues["ID"])"
#Put the fieldvalues in variables.
$Managerf = $item.FieldValues[$SPListItemColumns.Managerf]
$Managerf = $Managerf.LookupValue
Write-Output $Managerf
$ListItem[$SPListItemColumns.Accountnaam] = "sgouman#test.nl"
$ListItem.Update()
$Context.ExecuteQuery()
}
}
But whenever I run this script I get this error:
Exception calling "ExecuteQuery" with "0" argument(s): "There are invalid data used to update this listitem or the field is readonly."
so what could it be? I already tried with the user as email address and user as just the normal name none of these work. I want to update the name that is in office 365 so we can later use that field to email them.
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] : $_"}
}
}