user7140648
user7140648

Reputation: 23

Create a User in Active Directory via Powershellscript

I wanted to create a script to create a User through it in Active Directory. I already created a one-liner, which creates the User correctly. But know I want the script to create a User with different inputs.

I created the code, but somehow it doesn't work, can anybody elaborate what I did wrong?

$name=$args[0]
$givenname=$args[1]
$surname=$args[2]
$userlogin=$args[3]
$loginold=$args[4]
$description=$args[5]
$phone=$args[6]
$mail=$args[7]
$password=$args[8]
$passwordexpire=$args[9]
$locked=$args[10]
$oupath=$args[11]

echo $name
echo $givenname
echo $surname
echo $userlogin
echo $loginold
echo $description
echo $phone
echo $mail
echo $password
echo $passwordexpire
echo $locked
echo $oupath

New-ADUser -Name $name -GivenName $givenname -Surname $surname -UserPrincipalName $userlogin -SamAccountName $loginold -description $description -OfficePhone $phone -EmailAddress $mail -AccountPassword (Read-Host -AsSecureString "AccountPassword") $password -PasswordNeverExpires $passwordexpire -Enabled $locked -path $oupath

pause

Error message:

New-ADUser : Cannot validate argument on parameter 'Name'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
At C:\POwershell\Create_ad_user.ps1:27 char:18
+ New-ADUser -Name $name -GivenName $givenname -Surname $surname -UserPrincipalNam ...
+                  ~~~~~
    + CategoryInfo          : InvalidData: (:) [New-ADUser], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.NewADUser

Press Enter to continue...: 
PS C:\Users\Administrator\Desktop>

Upvotes: 1

Views: 183

Answers (1)

henrycarteruk
henrycarteruk

Reputation: 13227

Looks like AccountPassword isn't correct as you are prompting for it (Read-Host -AsSecureString "AccountPassword") then supplying it in $password directly afterwards.

When you've got a large amount of parameters to pass splatting is often a good idea as it makes everything much easier to read like so:

$Params = @{
    Name = $args[0]
    Givenname = $args[1]
    Surname = $args[2]
    UserPrincipalName = $args[3]
    SamAccountName = $args[4]
    Description = $args[5]
    OfficePhone = $args[6]
    EmailAddress = $args[7]
    AccountPassword = ConvertTo-SecureString -AsPlainText $args[8] -Force
    PasswordNeverExpires = $args[9]
    Enabled = $args[10]
    Path = $args[11]
}

Write-Output $Params

New-ADUser @Params

Upvotes: 2

Related Questions