How to do the while in password?

Hi, I want that when I create a new user its will ask me to enter a password for this user

and until I will not enter a complex password its will ask me the password again and again.

I crate this script but I am not sure what to put in While anyone can help?

do {
    New-ADUser @newuser -ErrorAction Stop 
catch [Microsoft.ActiveDirectory.Management.ADPasswordComplexityException]{
Write-Host  -ForegroundColor Yellow "The account is not enabled due password not meet the password policy"    
} while ($password -notlike [Microsoft.ActiveDirectory.Management.ADPasswordComplexityException])

May I recommend another approach? Instead of creating a password by hand you may create it automatically following the password rules of your company. It eliminates the need for a pesky loop forcing a human being to do the work of a computer. :wink:

Here you can find some examples from other people:

BTW: I recommended actually the same for your employee number loop in my first answer there. :wink:

yes your loop is very good thank you

i just don’t know what to put in While

No. I actually meant: Do not use a loop! :point_up_2:t4:

Again - what I meant was: Do not use a loop!

Did you take a look at some of the search hits in the Google search?

Hi Olaf i used this and now its working

type or paste Import-Module ActiveDirectory
Function Test-PasswordForDomain {
    Param (
        [Parameter(Mandatory=$false)][string]$AccountSamAccountName = "",
        [Microsoft.ActiveDirectory.Management.ADEntity]$PasswordPolicy = (Get-ADDefaultDomainPasswordPolicy -ErrorAction SilentlyContinue)

    If ($Password.Length -lt $PasswordPolicy.MinPasswordLength) {
        return $false

   if (($AccountSamAccountName) -and ($Password -match "$AccountSamAccountName")) {
        return $false
   if ($AccountDisplayName) {
    $tokens = $AccountDisplayName.Split(",.-,_ #`t")
    foreach ($token in $tokens) {
        if (($token) -and ($Password -match "$token")) {
            return $false
    return $true   
$password = Read-Host -Prompt "Enter password"

while(!(Test-PasswordForDomain -Password $password)){
    write-host -ForegroundColor Yellow "Password complexity error!!!"
    $password = Read-Host -Prompt "Enter password"


May I take a wild guess and say you did not write that code, right? Do you understand what this code does? It actually does NOT check the complexity. It only checks if it’s long enough and if it’s not the same like the sAMAccountName or if it contains some parts of the name of the user.

You should not use code you do not understand.

I’d stick to my recommendation to generate the password automatically according to the password rules of your company.

you right I did type the function but the reset of the script I did
and its working now so i think its ok