New-ADUser : The server is unwilling to process the request - powershell

I am using PS to add users to AD using input data from a CSV file, but I keep getting the error:
The code and csv will be attached to this post, any pointers or insight leading to a solution will be appreciated!
Import-Module ActiveDirectory
$ar_user = Import-Csv \\JHanDomain.local\Home\IT\IT_Share\a10\users.csv
foreach ($User in $ar_user)
{
$uname = $User.Username
$pw = $User.Password
$Fname = $User.FirstName
$Lname = $User.LastName
$ou = $User.OUPath
$desc = $User.Description
$action = $User.Action
$splat = #{
Name=$Uname
AccountPassword=(ConvertTo-SecureString $pw -AsPlainText -Force)
GivenName=$Fname
Surname=$Lname
DisplayName="$FName $LName"
Path=$ou
Description=$desc
Enabled=$true
}
if (Get-ADUser -F {AccountName -eq $Uname})
{
Write-Warning "User Already Exists!"
}
else
{
New-ADUser #splat
}
}
users.csv
Edit: The code works when I remove Path=$ou from $splat but I can't identify anything wrong with the path. I've tried switching "cn" for "ou" (in the CSV file) but same results. The path itself is correct.

The problem was with the OUPath in the input data:
cn=Bus_IT,dc=JHanDomain.local,dc=local
changed to
ou=Bus_IT,dc=JHanDomain,dc=local
Everything works

Related

AD-user script has no output

I'm creating a script for adding multiple users in Active Directory. I stumbled upon this link, when I couldn't get the guide described in the question to work either. I then tried one of the solutions in the comments
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)"
}
}
Here is my CSV file
firstname;lastname;username;password;ou
Mette;Frederiksen;MeFr;Password1;OU=Salg,OU=Users,OU=RGD Aarhus,DC=rgd,DC=local
Sussi;Hart;SuHa;Password1;OU=Salg,OU=Users,OU=RGD Aarhus,DC=rgd,DC=local
Ove;Tylstrup;OvTy;Password1;OU=Salg,OU=Users,OU=RGD Aarhus,DC=rgd,DC=local
Karlos;Mondolez;KaMo;Password1;OU=Lager,OU=Users,OU=RGD Aarhus,DC=rgd,DC=local
Anne;Otto;AnOt;Password1;OU=Lager,OU=Users,OU=RGD Aarhus,DC=rgd,DC=local
Dennis;Ågard;DeÅg;Password1;OU=Lager,OU=Users,OU=RGD Aarhus,DC=rgd,DC=local
Helena;Riss;HeRi;Password1;OU=Okonomi,OU=Users,OU=RGD Aarhus,DC=rgd,DC=local
Risa;Lamende;RiLa;Password1;OU=Okonomi,OU=Users,OU=RGD Aarhus,DC=rgd,DC=local
However, when I run the above code nothing happens
PS C:\Users\RGDAdmin> C:\Users\RGDAdmin\Documents\ADUser.ps1
PS C:\Users\RGDAdmin>
When I add the Delimiter parameter, I get this
Created new user 'KaMo' with initial password: Password1
New-ADUser : The directory service was unable to allocate a relative identifier
At C:\Users\RGDAdmin\Documents\ADUser.ps1:31 char:9
+ New-ADUser #userParams
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (CN=Anne Otto,OU...DC=rgd,DC=local:String) [New-ADUser], ADException
+ FullyQualifiedErrorId :
ActiveDirectoryServer:8208,Microsoft.ActiveDirectory.Management.Commands.NewADUser
PS. I know the password is bad practice in terms of passwords
Your file is delimited by semicolons, so you will definitely need to specify the -Delimiter parameter. But the documentation has a caveat:
To specify a semicolon (;) enclose it in single quotation marks.
So it should look like this:
$ADUsers = Import-Csv -Delimiter ';' -Path 'C:\Users\Desktop\Powershell files\EM-mis-new-AD.csv'
If that still results in that RID error, then there's possibly something wrong on the server. Can you create users manually using AD Users and Computers?
Try reviewing this. I don't have access to ActiveDirectory to test it myself.
#helpers
function usernameIsNotBlank {
[CmdletBinding()]
param(
$Username
)
[regex]$rx = "\S"
return $rx.match($Username)
}
function usernameDoesNotAlreadyExist {
[CmdletBinding()]
param(
$Username
)
$UserDoesNotExist = $true
$UserObject = $(
try {
Get-ADUser $Username
}
catch {
$null
}
)
if ($null -ne $UserObject) {
$UserDoesNotExist = $false
Write-Verbose "$Username already exists"
}
else {
$UserDoesNotExist = $true
}
return $UserDoesNotExist
}
function suppliedUsernameIsAvailable {
[CmdletBinding()]
param(
$Username
)
return ((usernameIsNotBlank -Username $Username) -and (usernameDoesNotAlreadyExist -Username $Username))
}
#script
$OriginalVerbose = $VerbosePreference
$VerbosePreference = "Continue"
Import-Module ActiveDirectory
$CSV = "C:\Users\Desktop\Powershell file\EM-mis-new-AD.csv"
$Data = Import-CSV $CSV
foreach ($Line in $Data) {
if (suppliedUsernameIsAvailable($Line.username)) {
New-ADUser -Name "$Line.firstname $Line.lastname" -GivenName "$Line.firstname" -Surname "$Line.lastname" -SamAccoutnname "$(Line.username)#mydomain.com" -AccountPassword (ConvertTo-SecureString $Line.password -AsPlainText -Force) -ChangePasswordAtLogon $true -Path "$Line.ou"
}
}
$VerbosePreference = $OriginalVerbose

New-ADUser : The object name has bad syntax. Powershell Docx import error

I am attempting to create new Active Directory users from a word document. However I am running into a problem during creation of the user wherein the script says "The object name has Bad Syntax" I have narrowed down the problem to the "New-ADUser:" portion of the code below
# Import active directory module for running AD cmdlets
Import-Module activedirectory
#Create word application object
$word = New-Object -ComObject Word.Application
#Assign document path
$documentPath = Read-host => [Enter Template to use Ex:"C:\Users\username\Desktop\employeeform.docx"]
#open the document
$document = $word.Documents.Open($documentPath)
#list all tables in doc
$document.Tables | ft
#get info from a certain part of the table
$pager = $document.Tables[1].Cell(4,2).range.text
$fname = $document.Tables[1].Cell(6,2).range.text
$lname = $document.Tables[1].Cell(8,2).range.text
$fn1 = $fname.Substring(0,1)
$username = "$fn1$lname"
$jobtitle = $document.Tables[1].Cell(15,2).range.text
$department = $document.Tables[1].Cell(16,2).range.text
$manager = $document.Tables[1].Cell(17,2).range.text
$pagernumber = $pager.Substring(17)
$template = Read-host => [Enter Template to use Ex:MedicalAssistant]
#folder = $User.folder
Write-Output $documentPath
Write-Output $template
#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."
pause
}
else
{
#User does not exist then proceed to create the new user account
New-ADUser `
-SamAccountName $username `
-Name "$fname $lname" `
-GivenName $fname `
-Surname $lname `
-Enabled $True `
-DisplayName "$lname $fname" `
-Company "Companyname" `
-AccountPassword (convertto-securestring "Password" -AsPlainText -Force)`
-HomeDrive "X:" `
-ScriptPath "K32.exe" `
-OtherAttributes #{pager=$pagernumber} `
-Title $jobtitle `
-Department $department `
-Description $jobtitle `
#-Manager $manager `
#-HomeDirectory $folder `
}
#Close the document
$document.close()
#Close Word
$word.Quit()
pause
After searching google it seems this problem occurred because of how I am importing the document into the script which makes the variables objects instead of strings but I am unsure of how else to import the document so that the variable imports as a string. I attempted to use | Out-String and this did not change my error message, so google may have led me astray.
Make sure the variables you read from the table are trimmed and not empty ($null).
Better recreate that table into a CSV where you have much more control over the data and don't have to fiddle with the Word.Application COM object.
Also I would recommend using Splatting the parameters to New-ADUser, so you can get rid of using all those nasty backticks (which will give you errors when there is anything other than a newline following it..)
$userProps = #{
SamAccountName = $username
Name = "$fname $lname"
GivenName = $fname
Surname = $lname
Enabled = $True
DisplayName = "$lname $fname"
Company = "Companyname"
AccountPassword = (ConvertTo-SecureString "Password" -AsPlainText -Force)
HomeDrive = "X:"
ScriptPath = "K32.exe"
OtherAttributes = #{pager=$pagernumber}
Title = $jobtitle
Department = $department
Description = $jobtitle
# Manager = $manager
# HomeDirectory = $folder
}
New-ADUser #userProps

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'

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)"
}
}

Individual passwords for AD user | Import via CSV

I am trying to import users to AD via CSV / PowerShell.
The import now works fine, the users and all attributes are correct, but it seems like the passwords are not imported correctly from my .csv.
Here is my .ps1 im using:
#Import required modules
Import-Module ActiveDirectory
#Prompt user for CSV file path
$filepath = Read-Host -Prompt "Enter Path of CSV"
$securePassword = ConvertTo-SecureString $pass -AsPlainText -Force
# Import the file into a variable
$users = Import-Csv $filepath -Delimiter ";"
#Loop through each row and gather information
ForEach ($user in $users) {
#Gather the user's information
$fname = $user.FirstName
$lname = $user.LastName
$uname = $user.Username
$email = $user.Email
$jtitle = $user.Title
$OUpath = $user.'Organizational Unit'
$pass = $user.Password
$SAM = $user.SAM
#Create new AD user for each user in CSV file
New-ADUser -Name "$fname $lname" -GivenName $fname -Surname $lname -UserPrincipalName $uname -SamAccountName $SAM -Path $OUpath -AccountPassword $securePassword -PasswordNeverExpires $true -Enabled $true -EmailAddress $email
# Echo for every user created
}
Does anybody have a clue what the reason could be here?
Thanks,
Marius
You are converting $pass to secure string before it is imported from the csv. So the fixed one:
#Import required modules
Import-Module ActiveDirectory
#Prompt user for CSV file path
$filepath = Read-Host -Prompt "Enter Path of CSV"
# Import the file into a variable
$users = Import-Csv $filepath -Delimiter ";"
#Loop through each row and gather information
ForEach ($user in $users) {
#Gather the user's information
$fname = $user.FirstName
$lname = $user.LastName
$uname = $user.Username
$email = $user.Email
$jtitle = $user.Title
$OUpath = $user.'Organizational Unit'
$pass = $user.Password
$SAM = $user.SAM
$securePassword = ConvertTo-SecureString $pass -AsPlainText -Force
# The Rest