Create OU´s and Active Directory users in PowerShell? - 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.

Related

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

how to update custom attribute in active directory?

Hi guys my name is Bastian and I am a student. I come to ask for help on a script to update users in active directory with CSV file. I created the columns in the active directory schema, all appear in the user profile when I look for them, but when I perform the update the message says that the parameter does not exist. The updates through PowerShell directly works and is reflected, but through the CSV file does not find the columns, I need your help to correct my error, I would appreciate your guidance.
Import-Module ActiveDirectory
[String]$Ruta = Read-Host "path (Por Ejemplo
C:\archivocsv.csv)"
$ou="OU=DominioExtendido" + "," + (Get-ADDomain).DistinguishedName
If(-Not(Get-ADOrganizationalUnit -Filter {Name -eq "DominioExtendido"})){New-ADOrganizationalUnit
"DominioExtendido" -Path (Get-ADDomain).DistinguishedName}
$dominio=(Get-ADDomain).DNSRoot
Import-Csv -Path $Ruta | foreach-object {
$UPN = $_.Cuenta + "#" + "$dominio"
New-ADUser -SamAccountName $_.Cuenta -UserPrincipalName $UPN -Name $_.Nombre -DisplayName
$_.Nombre -SurName $_.Apellidos -GivenName $_.Nombres -Description $_.Descripcion -Office
$_.Oficina -OfficePhone $_.Telefono -EmailAddress $_.Email -Title $_.Titulo -Department
$_.Departamento -Company $_.Compania -City $_.Ciudad -State $_.Region -AccountPassword
(ConvertTo- SecureString $_.Clave -AsPlainText -force) -Path $ou -Enabled $true -
ChangePasswordAtLogon $true -Verbose -companyCode $_.CodigoEmpresa -companyID $._RutEmpresa -
socialReason $._razonSocial -acronymCountryCode $._CodigoPais -contractType $._TipoContrato -
businessUnity $._BU -officeLicence $._Licencia365}
""
finish!!
PS C:> ErrorTerminación(New-ADUser): "No se encuentra ningún parámetro que coincida con el nombre del
parámetro 'companyCode'." New-ADUser : No se encuentra ningún parámetro que coincida con el
nombre del parámetro 'companyCode'. En C:\Creacion_Masiva_Usuarios.ps1: 15 Carácter: 473+ ...
$true -Verbose - companyCode $_.Codigo_Empresa -companyID $._Rut_Empresa -socialR ...
CategoryInfo : InvalidArgument: (:) [New-ADUser], ParameterBindingException
FullyQualifiedErrorId :
NamedParameterNotFound,Microsoft.ActiveDirectory.Management.Commands.NewADUser
User attributes
Profile user
Use New-ADUser -OtherAttributes for attributes that don't have a corresponding parameter!
The -OtherAttributes parameter takes a hashtable as an argument, and you simply populate it with key-value entries where the key is the attribute display name and the value is the intended attribute value.
For an attribute with the display name companyCode, you'd supply a hashtable like this:
New-ADUser ... -OtherAttributes #{ 'companyCode' = $_.CodigoEmpresa }

add AD account with custom attribute using 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

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!

Add users to Active Directory

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!"