Search code examples
regexazurepowershellazure-cliazure-cli2

Azure-CLI/Powershell Password requirments


So i am trying to make a variable match the password requirements for making a virtual machine in azure CLI

to do this it must have 3 of the following !uppercase, 1 lowercase 1 special character or a number

This is the main code i am trying to change

$AdminPassword = Read-Host -Prompt "Please insert a Admin Password (Password must have 3 of the following: 1 lower case character, 1 upper case character, 1 number and 1 special character)"

This is the code i changed but isn't working correctly

do 
    {
        $AdminPassword = Read-Host -Prompt "Please insert a Admin Password (Password must have the 3 of the following: 1 lower case character, 1 upper case character, 1 number and 1 special character)"
    }
    until($AdminPassword -Like "[A-Z][A-Z][A-Z][a-z][a-z][a-z][0-9][0-9][0-9][!@$#$%^&*()_+\-=\[\]{};'':"\\|,.<>\/? ][!@$#$%^&*()_+\-=\[\]{};'':"\\|,.<>\/? ][!@$#$%^&*()_+\-=\[\]{};'':"\\|,.<>\/? ]")
    Write Match

with the write match line i know when it succeeds

the real trouble i have here is that i want all 4 of the requirements 3 times so 3 uppercase's 3 lowercase's etc and i also want to have the special characters but the # comments all the code that follows out like this

thanks in advance for reading this and posting your anwser!!!


Solution

  • I'm not sure if this can be done with just one regex.. As an alternative, below a small helper function to do the tests.

    function Test-AdminPassword {
        [CmdletBinding()]
        Param(
            [Parameter(Position = 0, Mandatory=$true)]
            [string]$Password,
    
            [Parameter(Position = 1)]
            [int]$Requirements = 5
        )
        $result = 0
    
        # test length between 12 and 24
        if ($Password.Length -in 12..24) {
            $result++
        }
        # test uppercase
        if (($Password -creplace '[^A-Z]', '').Length -ge 3) {
            $result++
        }
        # test lowercase
        if (($Password -creplace '[^a-z]', '').Length -ge 3) {
            $result++
        }
        # test digits
        if (($Password -replace '[^0-9]', '').Length -ge 3) {
            $result++
        }
        # test special characters
        if (($Password -creplace '[^!@$#%^&*()_+\-=\[\]{};'':"\\|,.<>\/? ]', '').Length -ge 3) {
            $result++
        }
    
        # return $true if the password complies with at least $requirements
        return ($result -ge $Requirements)
    }
    
    do {
        $AdminPassword = Read-Host -Prompt "Please insert an Admin Password (must have the 3 lower case characters, 3 upper case characters, 3 digits and 3 special characters)"
    } until (Test-AdminPassword $AdminPassword)