3

I'm trying to create a project that's creating users in active directory using powershell. All though, my problem is that let's say that I run this:

New-ADUser test1 -Givenname test -surname test -AccountPassword (ConvertTo-SecureString "abc" -AsPlainText -force)

As you know "abc" does not meet the password requirement, all though it adds the user anyways but without a password which in my project is not acceptable, I wan't to do this so if it fails in any parameter it should output the error without running the other parameters at all! I'd like this preferably in one line so I don't have to create scripts for it, just call it in my application. Tried multiple parameters such as -whatif and try, catch! Any kind of sources/answers are highly appreciated!

1 Answer 1

4

To clarify on the original post, this will return the error:

"New-ADUser : The password does not meet the length, complexity, or history requirement of the domain.".

The user account is created, but is disabled.

Specifying -ErrorAction Stop on the New-ADUser cmdlet is not sufficient to prevent the user account being created.

To prevent the user account from being created you must set the global ErrorActionPreference like so (and also use the ErrorAction parameter):

$ErrorActionPreference = "Stop"

If you wish you can wrap this around your New-ADUser cmdlet so that it only impacts that cmdlet and not the rest of your script, like so:

$ExistingEAP = $ErrorActionPreference
$ErrorActionPreference = "Stop"
New-ADUser ... -ErrorAction Stop
$ErrorActionPreference = $ExistingEAP  

For a more complete example, assuming you have a simple $userArray of samaccountnames for some generic accounts, you might try something like this:

$ExistingEAP = $ErrorActionPreference
$ErrorActionPreference = "Stop"
$userarray = "test1","test2","test3"
foreach($username in $userarray)
{
    try
    {
        New-ADUser $username -Givenname test -surname test -AccountPassword (ConvertTo-SecureString "abc" -AsPlainText -force) -ErrorAction Stop
        $created += @($username)
    }
    catch
    {
        $notcreated += @($username)
    }
}
$ErrorActionPreference = $ExistingEAP
Write-Output "Created $created"
Write-Output "Could not create: $notcreated"

This works for me in my environment.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.