Add users to Active Directory - powershell

I'm trying to use the script below to add new users to Active Direcroty but for some reason I keep gettings error messages:
The Script:
Import-Module ActiveDirectory
Import-Csv 'C:\Scripts\\AddUsers.csv' -Delimiter "," | ForEach-Object {
$userPrincinpal = $_."SAM" + "#domain.org"
New-ADUser
-Name $_.Name `
-GivenName $_."First_Name" `
-Surname $_."Last_Nimpoame" `
-Description "Student"
-Path $_."OU" `
-SamAccountName $_."SAM" `
-UserPrincipalName $userPrincinpal `
-AccountPassword (ConvertTo-SecureString "password2016" -AsPlainText -Force) `
-ChangePasswordAtLogon $true `
-Enabled $true
}
Write-Host "Done!"
The error message:
-Name : The term '-Name' 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:\Scripts\Add Bulk AD User CSV\add_ad_users2.ps1:5 char:2
+ -Name $_.Name `
+ ~~~~~
+ CategoryInfo : ObjectNotFound: (-Name:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
-Path : The term '-Path' 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:\Scripts\Add Bulk AD User CSV\add_ad_users2.ps1:9 char:2
+ -Path $_."OU" `
+ ~~~~~
+ CategoryInfo : ObjectNotFound: (-Path:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
I'm not sure why I keep getting those error messages since I already imported the ActiveDirectory Module.
Can you please help?!

You are missing a trailing backtick after the New-ADUser:
Import-Module ActiveDirectory
Import-Csv 'C:\Scripts\\AddUsers.csv' -Delimiter "," | ForEach-Object {
$userPrincinpal = $_."SAM" + "#domain.org"
New-ADUser `
-Name $_.Name `
-GivenName $_."First_Name" `
-Surname $_."Last_Nimpoame" `
-Description "Student"
-Path $_."OU" `
-SamAccountName $_."SAM" `
-UserPrincipalName $userPrincinpal `
-AccountPassword (ConvertTo-SecureString "password2016" -AsPlainText -Force) `
-ChangePasswordAtLogon $true `
-Enabled $true
}
Write-Host "Done!"

Related

How to resolve NewAD error with -Path $OU

I am currently trying to automate the creation of new users on my Active Directory.
However when I run my powershell here is the error that presents itself to me :
New-ADUser: Unable to validate argument on "Path" parameter. The argument is null or empty. Provide an argument that is not null or empty and try again.
At character Line: 23:19
+ -Path $ OR `
+ ~~~
+ CategoryInfo: InvalidData: (:) [New-ADUser], ParameterBindingValidationException
+ FullyQualifiedErrorId: ParameterArgumentValidationError, Microsoft.ActiveDirectory.Management.Commands.NewADUser
What can i do ?
Thanks for your help !
This is my code
$ADUsers = Import-csv E:\SCRIPT\newusers.csv
foreach ($User in $ADUsers)
{
$Username = $User.username
$Password = $User.password
$Firstname = $User.firstname
$Lastname = $User.lastname
$Description = $User.description
$OU = $User.ou
New-ADUser `
-SamAccountName $Username `
-UserPrincipalName "$Lastname#domaine.fr" `
-Name "$Firstname $Lastname" `
-GivenName $Firstname `
-Surname $Lastname `
-Enabled $True `
-ChangePasswordAtLogon $False `
-DisplayName "$Lastname, $Firstname" `
-Description $Description `
-AccountPassword $Password `
-Path $OU `
}
Your comment indicates the CSV file uses the ; semi-colon as delimiter character, but you neglect to add that to the Import-Csv cmdlet. Now it is trying to parse the data using the default comma , and because of that none of the fields have a correct value.
Replace the first line with
$ADUsers = Import-csv -Path 'E:\SCRIPT\newusers.csv' -Delimiter ';'
Other than that, have a look at using splatting, so you don't need those awkward backticks.

Import-Module ActiveDirectory powershell error

I am creating a script that asks the user for the first and last name and implements it in a group in Active Directory. Below shows how the script starts
Import-Module ActiveDirectory
#Get-Command New-ADUser -Syntax
$firstName = Read-Host -Prompt "Please enter the first name"
$lastName = Read-Host -Prompt "Please enter the last name"
The text below shows the body of the script where the information is put
New-ADUser `
-Name "$firstName $lastName" `
-GivenName $firstName `
-Surname $lastName `
-UserPrincipalName = "$firstName.lastname"
-EmailAddress "$firstName.$lastName#<domain>"
-ChangePasswordAtLogon 1 `
-Enabled 1 `
-StreetAddress "<info>" `
-Office "<info>" `
-State "<info>" `
-PostalCode "<info>" `
-Country "<info>" `
-Path "<path>"
I get an error that is shown below showing that objects are not found. The errors are shown below
-Name$firstName $lastName : The term '-Name$firstName $lastName' 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 line:9 char:5
+ -Name"$firstName $lastName" `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (-Name$firstName $lastName:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
-EmailAddress : The term '-EmailAddress' 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 line:13 char:5
+ -EmailAddress "$firstName.$lastName#irtc-tx.com"
+ ~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (-EmailAddress:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
-ChangePasswordAtLogon : The term '-ChangePasswordAtLogon' 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 line:14 char:5
+ -ChangePasswordAtLogon 1 `
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (-ChangePasswordAtLogon:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
I have checked spelling and that doesnt seem to be an issue. Is there an obvious mistake I am making?
This looks like you have a space after the backtick character. That is the danger of using that to do line breaks. A better way to do that if you like how it is organized better is to define a hashtable, then splat that to the cmdlet like this:
$UserParams = #{
Name = "$firstName $lastName"
GivenName = $firstName
Surname = $lastName
UserPrincipalName = "$firstName.lastname"
EmailAddress = "$firstName.$lastName#<domain>"
ChangePasswordAtLogon = 1
Enabled = 1
StreetAddress = "<info>"
Office = "<info>"
State = "<info>"
PostalCode = "<info>"
Country = "<info>"
Path = "<path>"
}
New-ADUser #UserParams
Remove trailing whitespaces after backticks (`) and place missing ones :)
New-ADUser `
-Name "$firstName $lastName" `
-GivenName $firstName `
-Surname $lastName `
-UserPrincipalName = "$firstName.lastname" `
-EmailAddress "$firstName.$lastName#<domain>" `
-ChangePasswordAtLogon 1 `
-Enabled 1 `
-StreetAddress "<info>" `
-Office "<info>" `
-State "<info>" `
-PostalCode "<info>" `
-Country "<info>" `
-Path "<path>"
Your example shows a space between -name and "$firstName $lastName" but the error shows differently. Double check that there's a space
You're also missing some backticks, one after the UserPrincipalName line and one after emailaddress line and you have an extra space after the first backtick.
New-ADUser `
-Name "$firstName $lastName" `
-GivenName $firstName `
-Surname $lastName `
-UserPrincipalName = "$firstName.lastname" `
-EmailAddress "$firstName.$lastName#<domain>" `
-ChangePasswordAtLogon 1 `
-Enabled 1 `
-StreetAddress "<info>" `
-Office "<info>" `
-State "<info>" `
-PostalCode "<info>" `
-Country "<info>" `
-Path "<path>"

Adding users via powershell script gives error

I am trying to ad users from a csv file to an OU with a powershell script but getting some error?
I'll post the line that I am using for adding the users. And I have checked that the retrieval path for the csv file is correct..
New-ADUser -SamAccountName $login -Name $namn -GivenName $Fname -Surname $Enamn -Department $user.Department -Division $user.Division -Title $user.role -Description $user.Extension -Office $user.Office -UserPrincipalName $login"#hqad.local" -path "OU=Carb_users,DC=HQAD,DC=Local" -EmailAddress $mail -AccountPassword (ConvertTo-SecureString -AsPlainText "Syp9393" -Force) -Enable $True
Error output:
New-ADUser : The server is unwilling to process the request
At C:\Users\Administrator\Desktop\Userscript.ps1:37 char:1
+ New-ADUser -SamAccountName $login -Name $namn -GivenName $Fname -Surn ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (CN=Carl Malm,OU...C=HQAD,DC=Local:String) [New-ADUser], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:0,Microsoft.ActiveDirectory.Management.Commands.NewADUser
Happy for any help!

Create OU´s and Active Directory users in PowerShell?

I tried to do an script in PowerShell to manage Organizative Units, users group and users but it doesn't work. My domain is ras2017.org. I am the domain Administrator, and I works with only 1 server machine.
#Creating the UO
New-ADOrganizationalUnit Profesorado
New-ADOrganizationalUnit Alumnado
#Creamos los grupos de usuarios
New-ADGroup -Name "Profesorado" -SamAccountName Profesorado -GroupCategory Security -GroupScope Global -DisplayName "Profesorado" -Path " OU=Profesorado,DC=ras2017,DC=org " -Description "Grupo del profesorado"
New-ADGroup -Name "Alumnado" -SamAccountName Alumnado -GroupCategory Security -GroupScope Global -DisplayName "Alumnado" -Path " OU=Alumnado,DC=ras2017,DC=org " -Description "Alumnado"
#Creating users
New-ADUser -Name Rafa -GivenName Rafa -Surname Aybar -Path "OU=Alumnado,DC=ras2017,DC=org" -accountPassword (ConvertTo-SecureString -AsPlainText "Rafa-1994" -Force)
New-ADUser -Name Al1 -GivenName Al1 -Surname 2 -Path "OU=Alumnado,DC=ras2017,DC=org" -accountPassword (ConvertTo-SecureString -AsPlainText "Rafa-1994" -Force)
New-ADUser -Name Al2-GivenName Al2 -Surname 2 -Path "OU=Alumnado,DC=ras2017,DC=org" -accountPassword (ConvertTo-SecureString -AsPlainText "Rafa-1994" -Force)
New-ADUser -Name Prof1 -GivenName 1 -Surname 1 -Path "OU=Profesorado,DC=ras2017,DC=org" -accountPassword (ConvertTo-SecureString -AsPlainText "Rafa-1994" -Force)
New-ADUser -Name Prof2 -GivenName 2 -Surname 2 -Path "OU=Profesorado,DC=ras2017,DC=org" -accountPassword (ConvertTo-SecureString -AsPlainText "Rafa-1994" -Force)
#adding users to groups
Add-ADGroupMember "Alumnado" Rafa,Al1,Al2
Add-ADGroupMember "Profesorado" Prof1,Prof2
It gives me this error:
PS C:\Users\Administrador.WIN-481D680G638> New-ADOrganizationalUnit "Profesorado"
New-ADOrganizationalUnit : No se pudo encontrar ningún servidor predeterminado
que ejecutara Servicios web de Active Directory.
En línea: 1 Carácter: 1
+ New-ADOrganizationalUnit "Profesorado"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ResourceUnavailable: (:) [New-ADOrganizationalUnit], ADServerDownException
+ FullyQualifiedErrorId : ActiveDirectoryServer:1355,Microsoft.ActiveDirectory.Management.Commands.NewADOrganizationalUnit
"PS C:\Users\Administrador.WIN-481D680G638>"
The above is the start of the error message you posted. This indicates to me that you are logged in as Administrator on machine WIN-481D680G638. Is this a domain controller? Is this a Network account?
" + CategoryInfo : ResourceUnavailable: (:) [New-ADOrganizationalUnit], ADServerDownException"
The above indicates that the script is not able to reach a computer hosting AD so it cannot create the OU. Try running a simple AD command as this user from this machine and see if it works. "Get-ADUser JDoe". Also you could run:
New-ADOrganizationalUnit Profesorado -Whatif
This will probably generate the same error. Hope this helps.

Bulk Add AD through Powershell/CSV issue

I am trying to bulk-add users into my Active Directory, but I am getting expression errors right at the start of the script. I am not a script buff at all, so I am really out of ideas from the get go.
$Users = Import-Csv ".\UsersFile.csv"
foreach ($User in $Users)
{
-OrganizationalUnit $User.OU
-SamAccountName $User.UserName
-userPassword $User.Password
-GivenName $User.First
-Initials $USer.Initial
-sn $User.Last
-Displayname $User.DisplayName
-Description $User.Description
-Physicaldeliveryofficename $User.Office
-TelephoneNumber $User.Tel
-Mail $User.mail
-streetaddress $User.Street
-postOfficeBox $User.Postbus
-l $User.Location
-st $User.Provincie
-postalCode $User.Postcode
-c $User.Land
-deparment $User.Department
-Company $User.Organisatie
-Manager $User.Manager
-Password $User.Password -ResetPasswordOnNextLogon $false
}
The error log.
Missing expression after unary operator '-'.
At C:\Users\Administrator\Desktop\CreateUserBulk.ps1:4 char:10
+ - <<<< OrganizationalUnit $User.OU `
+ CategoryInfo : ParserError: (-:String) [], Parseexception
+ FullyQualifiedErrorID : MissingExpressionAfterOperator
After trying the link (From serv) and editing the CSV and script accordingly, getting a lot more errors now with this.
Import-Csv : Cannot open file "C:\Users\administrator\UsersFile.csv".
At C:\Users\administrator\Desktop\Untitled3.ps1:2 char:20
+ $Users = Import-Csv <<<< -Delimiter ";" -Path ".\UsersFile.csv"
+ CategoryInfo : OpenError: (:) [Import-Csv], FileNotFoundException
+ FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.ImportCsvCommand
You cannot call a method on a null-valued expression.
At C:\Users\administrator\Desktop\Untitled3.ps1:9 char:53
+ $FirstLetterFirstname = $UserFirstname.substring <<<< (0,1)
+ CategoryInfo : InvalidOperation: (substring:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
ConvertTo-SecureString : Cannot bind argument to parameter 'String' because it is null.
At C:\Users\administrator\Desktop\Untitled3.ps1:11 char:195
+ New-ADUser -Name $Detailedname -SamAccountName $SAM -UserPrincipalName $SAM -DisplayName $Detailedname -GivenName
$user.firstname -Surname $user.name -AccountPassword (ConvertTo-SecureString <<<< $Password -AsPlainText -Force) -Ena
bled $true -Path $OU
+ CategoryInfo : InvalidData: (:) [ConvertTo-SecureString], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ConvertToSe
cureStringCommand
EDIT2: Fixed, I changed the source link to it's fullness and now it works!
You are not creating a new AD user in your script. So -OrganizationalUnit should be undefined and throw an error, excpet you declare them as a variable first.
Import-Module ActiveDirectory
$Users = Import-Csv -Delimiter ";" -Path ".\UsersFile.csv"
foreach ($User in $Users)
{
$FirstLetterFirstname = $User.firstname.substring(0,1)
New-ADUser -Name $User.firstname + " " + $User.name
-SamAccountName $FirstLetterFirstName + $User.name
//... and so on
}
You can declare all variables first in the manner of $FirstletterFirstName and execute the New-ADUser command at the end of each loop, which makes it easier to read and modify later on.
The important part stays: Adding a new user is executed through the New-ADUser command which you are missing. You can also add the New-ADUser to the top of your loop, which should make your query work if there are no other syntax errors / Spelling errors in your code
//EDIT: You can find a working example at http://gallery.technet.microsoft.com/scriptcenter/ed20b349-9758-4c70-adc0-19c5acfcae45
and the TechNet article for New-ADUser:
http://technet.microsoft.com/en-us/library/ee617253.aspx