Avatar of RAFA
RAFA
Flag for Venezuela, Bolivarian Republic of asked on

Script - PowerShell

Good afternoon,

I have the following doubt, I am creating a script to create a user in my Active Directory automatically with PowerShell ISE.

In the following script I want these two users to have the same password without having to type it twice, that is, when I am asked to enter the password for each user.

I want that at the moment of placing the password, I take it for these two users that I am creating as an example.

Someone who can guide me please.

Best regards.

$user = New-ADUser "Roberto"
$pwd = Read-Host "Ingresar Contraseña" -AsSecureString
$pwd = Set-ADAccountPassword Roberto -NewPassword $pwd
Enable-ADAccount Roberto
$user = New-ADUser "Rocio"
$pwd = Read-Host "Ingresar Contraseña" -AsSecureString
$pwd = Set-ADAccountPassword Rocio -NewPassword $pwd
Enable-ADAccount Rocio
PowershellSystem ProgrammingWindows OSActive Directory

Avatar of undefined
Last Comment
sirbounty

8/22/2022 - Mon
sirbounty

You were reassigning your $pwd variable...try this:
$pwd = Read-Host "Ingresar Contraseña" -AsSecureString

$user = New-ADUser "Roberto" 
Set-ADAccountPassword Roberto -NewPassword $pwd
Enable-ADAccount Roberto
$user = New-ADUser "Rocio"
Set-ADAccountPassword Rocio -NewPassword $pwd
Enable-ADAccount Rocio

Open in new window

sirbounty

And perhaps more efficient as a loop...
$pwd = Read-Host "Ingresar Contraseña" -AsSecureString

foreach ($username in @('Roberto','Rocio')) {
  $user = New-ADUser $username
  Set-ADAccountPassword $username -NewPassword $pwd
  Enable-ADAccount $username
}

Open in new window

RAFA

ASKER
Good afternoon,

Thanks for clarifying my doubt, the script did work and I apply the same password to all users.

But now I'm trying to add a certain number of users to a new organizational unit but they give me certain errors, the users create them but outside the organizational unit, I would like to see if you can help me with this new doubt.

Attach the script to powershell.


$pwd = Read-Host "Ingresar Contraseña" -AsSecureString
foreach ($username in @('Johana','David')) {
foreach ($ouname in @('Calidad')) {
  $user = New-ADUser $username
  $ou =  New-ADOrganizationalUnit $ouname
  Set-ADAccountPassword $username -NewPassword $pwd
  Enable-ADAccount $username
}
}
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
ASKER CERTIFIED SOLUTION
sirbounty

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.