add AD account with custom attribute using powershell - powershell

I am trying to add an account using powershell along with a cutom attribute. Schema extension is done and from attribute editor i can see that value of custom attribute "test" is not set.
$pw = "jakdakjdJAKJKA123";
$spw = ConvertTo-SecureString $pw -AsPlainText -force;
$accountname = "mytest";
$des = "Description";
$otherAttributes = #{'test' = "testval"};
New-AdUser -UserPrincipalName "$accountname#testdomain.local" -path "OU=Services,OU=Users,OU=OrgA,DC=testdomain,DC=local" -Name "$accountname" -SamAccountName "$accountname" -GivenName "$accountname" -Description $des -CannotChangePassword $true -DisplayName "$accountname" -PasswordNeverExpires $true -AccountPassword $spw -Enabled $true -otherAttributes $otherAttributes
when i run above code i get an error.
New-AdUser : The parameter is incorrect
At line:6 char:1
+ New-AdUser -UserPrincipalName "$accountname#testdomain.local" -path "OU=S ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (CN=mytest...testdomain,DC=local:String) [New-ADUser], ADInvalidOperationException
+ FullyQualifiedErrorId : ActiveDirectoryServer:87,Microsoft.ActiveDirectory.Management.Commands.NewADUser
if i remove "-otherAttributes $otherAttributes", account will be added successfully.
Question is how can i add account with custom attribute?

Take the email out of the UserPrincipalName
New-AdUser -UserPrincipalName "$accountname" -path "OU=Services,OU=Users,OU=OrgA,DC=testdomain,DC=local" -Name "$accountname" -SamAccountName "$accountname" -GivenName "$accountname" -Description $des -CannotChangePassword $true -DisplayName "$accountname" -PasswordNeverExpires $true -AccountPassword $spw -Enabled $true -otherAttributes $otherAttributes

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.

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!

can't create userS via powershell

I can't import users in powershell with a script via an csv file, but If I print the parameters on the screen,it shows them as it should.
what I am doing wrong? in my life plenty with that mustache, but plis focus on the script.
is running windows server 2016 on the powershell ise, on virtualbox
The Script:
If(-Not(Get-ADOrganizationalUnit -Filter {Name -eq "991-5D"}))
{New-ADOrganizationalUnit "991-5D" -Path (Get-ADDomain).DistinguishedName}
If(-Not(Get-ADOrganizationalUnit -Filter {Name -eq "911-5V"}))
{New-ADOrganizationalUnit "911-5V" -Path (Get-ADDomain).DistinguishedName}
$domain=(Get-ADDomain).DNSRoot
Import-Csv -Path "C:\Alumnos.csv" | foreach-object {
[int]$number= $_.X
If($number -ge 10 -and $number -le 26)
{
$UO="991-5D"
}
//there are many others O.U.
$ou= "UO="+$UO+","+$domain
$UPN = $_.LETRA+$_.PATERNO+$_.X+"#"+ "$domain"
$CUENTA= $_.LETRA+$_.PATERNO+$_.X
New-ADUser -SamAccountName $CUENTA -UserPrincipalName $CUENTA -Name $_.NOMBRE
-SurName $_.PATERNO -GivenName $_.NOMBRE -EmailAddress $UPN -AccountPassword
(ConvertTo-SecureString "Leica666" -AsPlainText -force) -Path $ou
-Enabled $true -ChangePasswordAtLogon $true -Verbose}
the data:
X,PATERNO,MATERNO,NOMBRE,SEGUNDO,LETRA
10,ARÉVALO,CORNEJO,NICOLÁS,ALEJANDRO,N
11,BARRIOS,MONTERO,BENJAMÍN,IGNACIO,B
12,BUSTAMANTE,LOYOLA,IGNACIO,HERNANDO,I
13,BUSTOS,GARRIDO,ARTURO,IGNACIO,A
this are the results on each line:
+ New-ADUser -SamAccountName $CUENTA -UserPrincipalName $CUENTA -Name $ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo:NotSpecified: (CN=IGNACIO,UO=9...da.com:String)
[New-ADUser], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:8335,
Microsoft.ActiveDirectory.Management.Commands.NewADUser
the head:
X,PATERNO,MATERNO,NOMBRE,SEGUNDO,LETRA
echo:
#{X=42; PATERNO=PAYACÁN; MATERNO=ZAPATA; NOMBRE=NICOLÁS; SEGUNDO=N; LETRA=}.NOMBRE
I know that reads the file and instead of reading just the column reads all the line($_), and then prints whatever I wrote next to it(".name", ".section", etc).
I've made some variable and format changes to make this code more successful.
$domain=Get-ADDomain
Import-Csv -Path "C:\Alumnos.csv" |
Foreach-Object {
[int]$number= $_.X
If($number -ge 10 -and $number -le 26)
{
$UO="991-5D"
}
$ou = "OU={0},{1}" -f $UO,$domain.DistinguishedName
$UPN = "{0}{1}{2}#{3}" -f $_.LETRA,$_.PATERNO,$_.X,$domain.DNSRoot
$CUENTA= "{0}{1}{2}" -f $_.LETRA,$_.PATERNO,$_.X
New-ADUser -SamAccountName $CUENTA -UserPrincipalName $UPN -Name $_.NOMBRE `
-SurName $_.PATERNO -GivenName $_.NOMBRE -EmailAddress $UPN `
-AccountPassword (ConvertTo-SecureString "Leica666" -AsPlainText -force) -Path $ou `
-Enabled $true -ChangePasswordAtLogon $true -Verbose
}
Explanation:
$domain: I've made this an ADDomain object. This allows the DistinguishedName and DNSRoot properties to be accessed where appropriate.
-f operator: I used the format operator to make it easier to read the string concatenation attempts.
$ou: This is constructed using the DistinguishedName of the domain. This is the proper format for the OU path.
$UPN: This is constructed using the DNSRoot of the domain. It can obviously be different than your domain, but must be in an email address or FQDN format.
Additional Comments:
You are setting -Name to be $_.NOMBRE. This could be problematic because Name must be unique in each OU. Name is used to build the CN, which is where uniqueness is required. If you have NICOLAS in OU 991-5D, you are going to get an error if you try to create another NICOLAS in the same place. IMHO, I would do something different. You could also implement the use of splatting for building the properties of your New-ADUser command, but that is only for readability purposes. Below is an example of splatting:
$NewUserProperties = #{
SamAccountName = $CUENTA
UserPrincipalName = $UPN
Name = $_.NOMBRE
Surname = $_.PATERNO
GivenName = $_.NOMBRE
EmailAddress = $UPN
AccountPassword = (ConvertTo-SecureString "Leica666" -AsPlainText -force)
Path = $ou
Enabled = $true
ChangePasswordAtLogon = $true
}
New-ADUser #NewUserProperties -Verbose

ADSI not validating correctly?

I have a CSV with 1500+ users there are 30 users per class OU, and then 6 class OU's per Intake OU. What I'm trying to achieve is, foreach (user in CSV), check if OU exists, then check if parent OU exists, create the parent OU only if it doesn't exist, then create the OU, then create the user, or just create the user if the OU exists.
Here is the code I'm using:
$ErrorActionPreference = "Stop"
Import-Module ActiveDirectory
$CSV = Import-Csv "C:\Scripts\AddPupils.csv"
foreach ($user in $CSV) {
# Variables
$GivenName = $user.GivenName
$SurName = $user.SurName
$UserName = $user.UserName
$Class = $user.YearClass
$Intake = $user.Intake
$DisplayName = $GivenName+" "+$SurName
# Create User
$UserOUParent = "OU=Year "+$iIntake+" Intake,OU=Students,OU=Users,OU=Roding,DC=Zulbag,DC=com"
$UserOU = "OU=Class "+$Class.Substring(1,1)+",OU=Year "+$iIntake+" Intake,OU=Students,OU=Users,OU=Roding,DC=Zulbag,DC=com"
$NewUserOUParentCheck = [ADSI]::Exists("LDAP://$UserOUParent")
$NewUserOUCheck = [ADSI]::Exists("LDAP://$UserOU")
if ($NewUserOUCheck -eq $false){
if ($NewUserOUParentCheck -eq $false){
"Create Parent Ou"
New-ADOrganizationalUnit `
-Name ("Year "+$Intake+" Intake") `
-Path "OU=Students,OU=Users,OU=Roding,DC=Zulbag,DC=Com" `
-ProtectedFromAccidentalDeletion $False
}
"Create OU"
New-ADOrganizationalUnit `
-Name ("Class "+$Class.Substring(1,1)) `
-Path ("OU=Year "+$Intake+" Intake,OU=Students,OU=Users,OU=Roding,DC=Zulbag,DC=Com") `
-ProtectedFromAccidentalDeletion $False
}
"Create User"
New-ADUser `
-Name $DisplayName `
-SurName $SurName `
-GivenName $GivenName `
-DisplayName $DisplayName `
-SamAccountName $UserName `
-UserPrincipalName ($UserName+"#Zulbag.com") `
-AccountPassword (ConvertTo-SecureString "Testing123" -AsPlainText -force) `
-CannotChangePassword $true `
-ChangePasswordAtLogon $false `
-PasswordNeverExpires $true `
-EmailAddress ($UserName+"#Zulbag.com") `
-Country "GB" `
-Path ("OU=Class "+$Class.Substring(1,1)+",OU=Year "+$Intake+" Intake,OU=Students,OU=Users,OU=Roding,DC=Zulbag,DC=Com") `
-ProfilePath ("D:\Shares\User Accounts\Students\Intake Year "+$Intake+"\Class "+$Class.Substring(1,1)+"\Profiles\"+$DisplayName) `
-Enabled $true
Start-Sleep -Seconds 5
# Add To Group
$Group = "CN=Redirection "+$Intake.Substring(2,2)+$Class.Substring(1,1)+",OU=Intake "+$Intake+",OU=Security Groups,OU=Roding,DC=Zulbag,DC=Com"
$GroupOU = "OU=Intake "+$Intake+",OU=Folder Redirection Groups,OU=Security Groups,OU=Roding,DC=Zulbag,DC=Com"
$NewGroupCheck = [ADSI]::Exists("LDAP://$Group")
$NewGroupOUCheck = [ADSI]::Exists("LDAP://$GroupOU")
if ($NewGroupCheck -eq $false) {
if ($NewGroupOUCheck -eq $false) {
"Create OU"
New-ADOrganizationalUnit `
-Name ("Intake "+$Intake) `
-Path "OU=Folder Redirection Groups,OU=Security Groups,OU=Roding,DC=Zulbag,DC=Com" `
-ProtectedFromAccidentalDeletion $False
}
"create Group"
New-ADGroup `
-Name ("Redirection "+$Intake.Substring(2,2)+$Class.Substring(1,1)) `
-GroupScope "Global" `
-Path ("OU=Intake "+$Intake+",OU=Folder Redirection Groups,OU=Security Groups,OU=Roding,DC=Zulbag,DC=Com")
}
"Add Member"
Add-ADGroupMember ("Redirection "+$Intake.Substring(2,2)+$Class.Substring(1,1)) $UserName
}
pause
Sample CSV:
GivenName,SurName,Class,UserName,Intake
Ali,Grisdale,1B,AGris,2016
Ayomiposi,Olayera,1B,AOlay,2016
In tests with Write-Output, the [ADSI] validates correctly but it appears to be validating it incorrectly here, the error message I keep getting is:
New-ADOrganizationalUnit : An attempt was made to add an object to the
directory with a name that is already in use
At C:\Scripts\AddPupils-Afzal.ps1:24 char:13
+ New-ADOrganizationalUnit
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (OU=Year 2016 In...C=Zulbag,DC=Com:String) [New-ADOrganizationalUnit], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:8305,Microsoft.ActiveDirectory.Management.Commands.NewADOrganizationalUnitdirectory
It successfully creates the parent OU, class OU and user, but fails to create the second user, instead validates the OU incorrectly again.
Any Ideas?
Check the script for path errors!

PowerShell New-ADUser : Cannot bind parameter because parameter 'OtherAttributes' is specified more than once

I'm trying to automate AD user creation with PowerShell.
This is the code:
Create AD User
New-ADUser -Name $DisplayName `
-SamAccountName $SamAccountName `
-GivenName $FirstName `
-Surname $LastName `
-DisplayName $DisplayName `
-AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) `
-Enabled $true `
-PasswordNeverExpires $False `
-ChangePasswordAtLogon $True `
-UserPrincipalName $UserPrincipalName `
-EmailAddress $PrimaryEmailAddress `
-OtherAttributes #{'proxyAddresses' = $proxyAddressesEmailMandatory} `
-OtherAttributes #{'ipPhone' = $UserExtension} `
Attribute "proxyAddress" is necessary so we can have Azure AD Sync between on-premise AD and Azure AD.
But now, we are trying to connect FreePBX with on-premise AD. In order to achieve that, we need to have "ipPhone" attribute.
Before I added last line, script was working fine.
I can see where the problem is, but I don't know how to fix it. Help with an example would be appreciated.
New-ADUser -Name $DisplayName `
-SamAccountName $SamAccountName `
-GivenName $FirstName `
-Surname $LastName `
-DisplayName $DisplayName `
-AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) `
-Enabled $true `
-PasswordNeverExpires $False `
-ChangePasswordAtLogon $True `
-UserPrincipalName $UserPrincipalName `
-EmailAddress $PrimaryEmailAddress `
-OtherAttributes #{
'proxyAddresses' = $proxyAddressesEmailMandatory
'ipPhone' = $UserExtension
}