Azure-CLI / Powershell密码要求

时间:2018-10-16 13:59:36

标签: regex azure powershell azure-cli azure-cli2

所以我试图使一个变量与在Azure命令行中制作虚拟机的密码要求相符

为此,它必须具有以下三个大写字母,1个小写字母,1个特殊字符或数字

这是我要更改的主要代码

$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)"

这是我更改的代码,但无法正常工作

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

使用写入匹配行,我知道它何时成功

我在这里遇到的真正麻烦是,我希望所有4个要求都满足3次,所以3个大写字母和3个小写字母等等 而且我也想拥有特殊字符 但是#注释了like this

之后的所有代码

在此先感谢您阅读并发布您的答案!

2 个答案:

答案 0 :(得分:3)

我不确定是否可以仅使用一个正则表达式来完成。 或者,在下面的一个小助手功能下进行测试。

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)

答案 1 :(得分:1)

对于特殊字符,正则表达式应为以下代码中的正则表达式。

您需要在正则表达式中使用单引号:

do
{
$s=Read-Host -Prompt "please enter a password"
}
until($s -like '[A-Z][A-Z][A-Z][a-z][a-z][a-z][0-9][0-9][0-9][!@$#$%^&*()_+\-\=`[`]{};'':`"\\|,.<>\/? ][!@$#$%^&*()_+\-\=`[`]{};'':`"\\|,.<>\/? ][!@$#$%^&*()_+\-\=`[`]{};'':`"\\|,.<>\/? ]')

write-host "complete entering password"

测试结果如下: enter image description here