Bulk AD Users Creation - powershell

I am working on a PowerShell command where I have a .csv file with a certain attributes, but am actually stuck in completing it.
The attributes of my .csv file are in the following order:
userPrincipalName
sAMAccountName
password
givenName
sn
displayName
description
Path
title
company
memberOf
department
mustChangePassword
My current code is this:
$Users = Import-Csv -Path "C:\BulkUsers.csv"
foreach ($User in $Users)
{
$UPN = $User.userPrincipalName
$SAM = $User.sAMAccountName
$Password = $User.password
$UserFirstname = $User.givenName
$UserLastname = $User.sn
$Displayname = $User.givenName + " " + $User.sn
$Description = $User.description
$Path = $User.Path
$Title = $User.title
$Company = $User.company
$Group = $User.memberOf
$Department = $User.department
New-ADUser -UserPrincipalName $UPN -SamAccountName $SAM -AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) -GivenName "$UserFirstname" -Surname "$UserLastname" -DisplayName "$Displayname" -Description "$Description" -Path "$Path" -title "$Title" -company "$Company" -memberOf "$Group" -department "$Department" -ChangePasswordAtLogon $true
}
Am getting the below error while executing it:
New-ADUser : A parameter cannot be found that matches parameter name 'memberOf'.
At line:15 char:292
+ ... any "$Company" -memberOf "$Group" -department "$Department" -ChangePasswordAtLo ...
+ ~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [New-ADUser], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.ActiveDirectory.Management.Commands.NewADUser

The error message is pretty straightforward. If you take a look at the documentation for the New-ADUser cmdlet you'll see that it doesn't have a parameter -memberOf. To add the newly created user to a group use the Add-ADGroupMember cmdlet.
$Account = New-ADUser ... -PassThru
Add-ADGroupMember -Identity $Group -Members $Account
This is assuming that the memberOf field from the CSV contains just a single group name or distinguished name.
The additional parameter -PassThru allows you to assign the created account object to a variable, so you can use that variable in the group assignment. Without that parameter New-ADUser runs silently (without output).

Related

Powershell issue when creating new user then give them group and move to specific OU

I'm quite new to PowerShell and still at entry-level. I'm running into an issue with my script and hope to seek some help here.
The objective I wanted to achieve is:
Create new users from .csv where their attribute values are filled
bases on their jobtitle: Add different groups, move the user to different OU
My script did work with user account creation and adding groups, but after I added the OU moving part, it failed. I'm attaching my script here and the error message, any advice would be really really helpful!!
Thank you very much in advance.
Import-Module activedirectory
$ADUsers = Import-csv 'D:\OneDrive - testit\IT Dept\PowerShell\Scripts\Case_Study\New_Employee_Action\RA_Test3.csv'
foreach ($User in $ADUsers)
{
$Lastname = $User.EnglishLastName
$Firstname = $User.EnglishFirstName
$department = $User.Department
$Username = $User.Account
$Password = $User.Password
$email = $User.Email
$displayname= $User.Displayname
$employeeid = $User.EmployeeID
$employeenumber = $User.EmployeeNumber
$OU = "OU=Rachel test,OU=Users,OU=testit,DC=testit,DC=edu,DC=cn"
$city = $User.city
$zipcode = $User.Zipcode
$jobtitle = $User.JobTitle
$company = $User.Company
$employeeType = $User.employeeType
if (Get-ADUser -F {SamAccountName -eq $Username})
{
Write-Warning "A user account with username $Username already exists in Active Directory."
}
else
{
New-ADUser `
-SamAccountName $Username `
-UserPrincipalName "$Username#testit.edu.cn" `
-Name "$Firstname $Lastname" `
-GivenName $Firstname `
-Surname $Lastname `
-Enabled $True `
-DisplayName "$displayname" `
-Path $OU `
-EmployeeID $employeeid `
-EmployeeNumber $employeenumber `
-City $city `
-PostalCode $zipcode `
-Title $jobtitle `
-Company $company `
-Department $department `
-EmailAddress $email `
-AccountPassword (convertto-securestring $Password -AsPlainText -Force) -ChangePasswordAtLogon $True `
-OtherAttributes #{'employeeType'=$employeeType}
}
$RA_Groups = #("Chinese Staff","$testStaffUsers","testUsers","Research Assistants")
$OU_RA = "OU=Research Assistant,OU=Academic,OU=Staff,OU=Users,OU=testit,DC=testit,DC=edu,DC=cn"
ForEach ($ADUser in $ADUsers)
{
if($jobtitle -eq 'Research Fellow (RF)'){
foreach($RA_Group in $RA_Groups){
Add-ADGroupMember -Identity $RA_Group -Members $Username
}
Move-ADObject -Identity $Username -TargetPath $OU_RA
Write-Output "Moved Account $($Username) to $($OU_RA)"
Write-Output "User $($Username) has been added to group $($RA_Groups)"
}
}
}
Add-ADGroupMember : Cannot find an object with identity: '' under: 'DC=testit,DC=edu,DC=cn'.
At D:\OneDrive - testIT\IT Dept\PowerShell\Scripts\Case_Study\New_Employee_Action\New_Employee_test.ps1:88 char:17
+ ... Add-ADGroupMember -Identity $RA_Group -Members $Username
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (:ADGroup) [Add-ADGroupMember], ADIdentityNotFoundException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.AddADGroupMember
Move-ADObject : Cannot find an object with identity: 'test.RA' under: 'DC=testit,DC=edu,DC=cn'.
At D:\OneDrive - testit\IT Dept\PowerShell\Scripts\Case_Study\New_Employee_Action\New_Employee_test.ps1:90 char:13
+ Move-ADObject -Identity $Username -TargetPath $OU_RA
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (test.RA:ADObject) [Move-ADObject], ADIdentityNotFoundException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.MoveADObject
Moved Account test.RA to OU=Research Assistant,OU=Academic,OU=Staff,OU=Users,OU=testit,DC=testit,DC=edu,DC=cn
User test.RA has been added to group Chinese Staff testUsers Research Assistants
There seem to be two problems here:
Move-ADObject : Cannot find an object with identity: 'test.RA'
Move-ADObject does not take the samaccountname as an input - the documentation indicates it wants either a distinguished name or a GUID. To solve this, once you have created the account, you can either Get-ADUser the username (to get the GUID / DN) or bodgy it up using your already known values from the script - I'd recommend using Get-ADUser for simplicity
$dn = Get-ADUser $username | Select-Object -expand DistinguishedName
Move-ADObject -Identity $dn -TargetPath $OU_RA
Add-ADGroupMember : Cannot find an object with identity: ''
You've defined the groups with names, but one is defined as a variable instead - it's likely here you're experiencing the error. You can see in the below that $testStaffUsers is a variable (identified by the $). Removing the $, or ensuring the variable is defined, would resolve the problem.
$RA_Groups = #("Chinese Staff","$testStaffUsers","testUsers","Research Assistants")
would become
$RA_Groups = #("Chinese Staff","testStaffUsers","testUsers","Research Assistants")

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 issue with a defined variable

I am pretty new to powershell and have a code that I found. I had it working but now it is no longer working. I didn't change anything with the variable so I am not sure what is going on. Here is a link to a Screenshot of the code and error. Please let me know if you need any other information
https://imgur.com/a/ntEhdoV
Thank you!
Import-Module activedirectory
$ADUsers = Import-csv 'C:\Users\Desktop\Powershell files\EM-mis-new-AD.csv'
foreach ($User in $ADUsers)
{
$Username = $User.username
$Password = $User.password
$Firstname = $User.firstname
$Lastname = $User.lastname
$OU = $User.ou
$Password = $User.Password
if (Get-ADUser -F {SamAccountName -eq $Username})
{
Write-Warning "A user account with username $Username already exist in Active Directory."
}
else
{
New-ADUser `
-SamAccountName $Username `
-UserPrincipalName "$Username#Mydomain" `
-Name "$Firstname $Lastname" `
-GivenName $Firstname `
-Surname $Lastname `
-Enabled $True `
-DisplayName "$Firstname, $Lastname" `
-Path $OU `
-AccountPassword (convertto-securestring $Password -AsPlainText -Force) -ChangePasswordAtLogon $True
}
}
Error:
Get-ADUser : Variable: 'Username' found in expression: $Username is not defined.
At C:\Users\jcarnovale\Desktop\Testing if.ps1:22 char:6
if (Get-ADUser -F {SamAccountName -eq $Username})
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : InvalidArgument: (:) [Get-ADUser], ArgumentException
FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.ArgumentException,Microsoft.ActiveDirectory.Management.Commands.GetADUse
You probably want to check that you have a good username before proceeding in the script, like:
$Username = $User.username
...
if(!$Username) {
throw "Username was empty!"
}
Also, try changing the Get-ADUser filter to use a string:
if (Get-ADUser -F "SamAccountName -eq $Username")
{
}
You didn't show us anything of the imported CSV file itself and I think the main problem is in there.
Import-Csv by default expects the comma (,) to be used as delimiter character. If that is not the case in your file, you need to add parameter -Delimiter followed by the character that is used as separator in your file (like -Delimiter ';' if your file uses the semicolon).
Please check that first, so the Import-Csv cmdlet can parse the file correctly.
Next, it could be that there are empty values in the username column and if so, the code should skip these rows.
Also, as commented, the -Filter parameter needs a double-quoted string "Property -eq 'something'" in which a variable like $username is expanded, instead of a scriptblock {..}
Finally, I'd recommend using Splatting on cmdlets that take many properties instead of using backticks.
Try
Import-Module ActiveDirectory
# this defaults to csv fields delimited by a comma. If your CSV file uses a different
# character, then add parameter '-Delimiter' followed by the actual character
$ADUsers = Import-Csv -Path 'C:\Users\Desktop\Powershell files\EM-mis-new-AD.csv'
# the Where-Object clause is just a precaution to omit records that have no username value
$ADUsers | Where-Object { $_.username -match '\S'} | ForEach-Object {
$Username = $_.username
if (Get-ADUser -Filter "SamAccountName -eq '$Username'" -ErrorAction SilentlyContinue) {
Write-Warning "A user account with SamAccountName '$Username' already exist in Active Directory."
}
else {
$Firstname = $_.firstname
$Lastname = $_.lastname
# use splatting on cmdlets that use a lot of parameters
$userParams = #{
SamAccountName = $Username
UserPrincipalName = "$Username#Mydomain.com"
Name = "$Firstname $Lastname"
GivenName = $Firstname
Surname = $Lastname
Enabled = $true
DisplayName = "$Firstname, $Lastname"
Path = $_.ou
AccountPassword = (ConvertTo-SecureString $_.Password -AsPlainText -Force)
ChangePasswordAtLogon = $true
}
# create the user and report back
New-ADUser #userParams
Write-Host "Created new user '$Username' with initial password: $($_.Password)"
}
}

Running my poweshell script produces an error and doesn't onboard new users

I am trying to on-board users utilizing Powershell for the company I am working for, however I am coming into an issue that states the directory object is not found. Can anyone assist me with what my error is and how to fix it?
I have tried to remove the city, organizational unit and have tried editing my excel csv file several times, but all tests have failed
# 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:\Users\padmin\Documents\users.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
$streetaddress = $User.streetaddress
#$city = $User.city
$zipcode = $User.zipcode
$state = $User.state
$country = $User.country
$telephone = $User.telephone
$jobtitle = $User.jobtitle
$company = $User.company
$department = $User.department
$Password = $User.Password
#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#greenkeyllc.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 `
-AccountPassword (convertto-securestring $Password -AsPlainText -Force) -ChangePasswordAtLogon $True
}
}
Expected results is to add a user into the proper organizational unit (different office locations) within the local active directory. The actual results are the error below.
New-ADUser : Directory object not found
At C:\Users\padmin\Documents\bulk_users1.ps1:41 char:3
+ New-ADUser `
+ ~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (CN=Bob Jake,CN=...eenkey,DC=local:String) [New-ADUser], ADIdentityNotFoundException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.NewADUser
-Company : The term '-Company' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included,
verify that the path is correct and try again.
At C:\Users\padmin\Documents\bulk_users1.ps1:51 char:13
+ -Company $company `
+ ~~~~~~~~
+ CategoryInfo : ObjectNotFound: (-Company:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
The # commented out line in the middle of the script breaks your expected line continuation:
-Path $OU `
#-City $city `
-Company $company `
Put the arguments in to a hashtable and splat them instead:
$NewADUserArgs = #{
SamAccountName = $Username
UserPrincipalName = "$Username#greenkeyllc.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
AccountPassword = (convertto-securestring $Password -AsPlainText -Force)
ChangePasswordAtLogon = $true
}
New-ADUser #NewADUserArgs
Now you can easily comment out a single entry in the argument table without worrying about line breaks and all those pesky backticks

Trying to mass-create AD users with a script and add them to a group listed in a CSV file. Not sure what I'm missing

I'm writing a powershell script for adding and grouping members from info in a CSV. I've done this before on a smaller scale, using a similar method, and it has worked for me. This time, however, it's throwing up a very non-specific error and I'm not sure how to continue.
$userlist = Import-Csv C:\Users\Administrator\Desktop\olygearusers.csv
$surname = $userlist.surname
$passwds = $userlist.accountpassword
$enabled = $userlist.enabled
$givennames = $userlist.givenname
$paths = $userlist.path
$city = $userlist.city
$addresses = $userlist.street
$phones = $userlist.phone
$group = $userlist.group
ForEach($givennames in $userlist){
if ($city -eq "calgary")
{new-aduser -AccountPassword (ConvertTo-SecureString $passwds -asplaintext -force) `
-Enabled:([bool]([int]$Enabled )) `
-GivenName $givennames `
-surName $surname `
-Name "'$givenname' '$surname'" `
-path $paths `
-SamAccountName "'$givennames'.'$surname'.'C'" `
-UserPrincipalName "'$givennames'.'$surname'.'C'.'#olygear.ca'" `
-streetaddress $addresses `
-homephone $phones `
-city $city `
-HomeDirectory '\\calgary3\homefolders\%username%' `
-HomeDrive 'S' `
-PassThru | Add-ADGroupMember -identity $group -Members $_.samaccountname}
else
{...}
}
Cannot convert the "System.Object[]" value of type "System.Object[]" to type "System.Int32".
At line:14 char:10
+ {new-aduser -AccountPassword (ConvertTo-SecureString $passwds ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [], RuntimeException
+ FullyQualifiedErrorId : ConvertToFinalInvalidCastException
Again, I've used this method before (albeit much simpler and not trying to add group membership during the process) but I'm not sure how to continue. Any help would be appreciated.
Just rearranging the elements of your code, you can accomplish what you want:
$userlist = Import-Csv C:\Users\Administrator\Desktop\olygearusers.csv
ForEach($user in $userlist){
$surname = $user.surname
$passwds = $user.accountpassword
$enabled = $user.enabled
$givennames = $user.givenname
$paths = $user.path
$city = $user.city
$addresses = $user.street
$phones = $user.phone
$group = $user.group
if ($city -eq "calgary")
{
$NewUser = #{
AccountPassword = ConvertTo-SecureString $passwds -asplaintext -force
Enabled = [bool][int]$enabled
GivenName = $givennames
surName = $surname
Name = "$givenname $surname"
Path = $paths
SamAccountName = "$givennames.$surname.C"
UserPrincipalName = "$givennames.$surname.C.#olygear.ca"
streetaddress = $addresses
homephone = $phones
city = $city
HomeDirectory = '\\calgary3\homefolders\%username%'
HomeDrive = 'S'
}
New-ADUser #NewUser
Add-ADGroupMember -identity $group -Members $samaccountname
}
else
{...}
}
Your code currently assigns all of your variables only once. In each assignment, you are creating an array of values. When you run your foreach loop, you are using the same array values for each iteration. Many of those parameters cannot accept an array and therefore throw errors. Using the current object ($user) each iteration of the foreach loop, you avoid this problem.