PowerShell - Password Generator - How to always include number in string?

前端 未结 8 1612
长情又很酷
长情又很酷 2020-12-19 06:17

I have the following PowerShell script that creates a random string of 15 digits, for use as an Active Directory password.

The trouble is, this works great most of t

8条回答
  •  温柔的废话
    2020-12-19 06:54

    Another solution:

    function New-Password() {
        param(
            [int] $Length = 10,
            [bool] $Upper = $true,
            [bool] $Lower = $true,
            [bool] $Numeric = $true,
            [string] $Special
        )
    
        $upperChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        $lowerChars = "abcdefghijklmnopqrstuvwxyz"
        $numericChars = "0123456789"
    
        $all = ""
        if ($Upper) { $all = "$all$upperChars" }
        if ($Lower) { $all = "$all$lowerChars" }
        if ($Numeric) { $all = "$all$numericChars" }
        if ($Special -and ($special.Length -gt 0)) { $all = "$all$Special" }
    
        $password = ""
        for ($i = 0; $i -lt $Length; $i++) {
            Write-Host "password: [$password]"
            $password = $password + $all[$(Get-Random -Minimum 0 -Maximum $all.Length)]
        }
    
        $valid = $true
        if ($Upper -and ($password.IndexOfAny($upperChars.ToCharArray()) -eq -1)) { $valid = $false }
        if ($Lower -and ($password.IndexOfAny($lowerChars.ToCharArray()) -eq -1)) { $valid = $false }
        if ($Numeric -and ($password.IndexOfAny($numericChars.ToCharArray()) -eq -1)) { $valid = $false }
        if ($Special -and $Special.Length -gt 1 -and ($password.IndexOfAny($Special.ToCharArray()) -eq -1)) { $valid = $false }
    
        if (-not $valid) {
            $password = New-Password `
                -Length $Length `
                -Upper $Upper `
                -Lower $Lower `
                -Numeric $Numeric `
                -Special $Special
        }
    
        return $password
    }
    

    Flexible enough to set length, turn on/of upper, lower, and numeric, and set the list of specials.

提交回复
热议问题