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

前端 未结 8 1606
长情又很酷
长情又很酷 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:53

    I've created this. You can choose how many Pwd to create

    $howoften = Read-Host "How many would you like to create: "
    $i = 0
    do{
        (-join(1..42 | ForEach {((65..90)+(97..122)+(".") | % {[char]$_})+(0..9)+(".") | Get-Random}))
        $i++
    } until ($i -match $howoften)
    

    To change the length of the pwd simply edit the "42" in line 4

    (-join(1..**42** | ForEach ...
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-19 06:57

    I had the same issue here is the snippet I used to create my alphanumerical password its simple all I have done is used ASCII regex replace to make it nice.

    Function Password-Generator ([int]$Length)
    {
        # Generate passwords just call password-generator(lenght of password)
        $Assembly = Add-Type -AssemblyName System.Web
        $RandomComplexPassword = [System.Web.Security.Membership]::GeneratePassword($Length,2)
        $AlphaNumericalPassword = $RandomComplexPassword -replace '[^\x30-\x39\x41-\x5A\x61-\x7A]+'
        Write-Output $AlphaNumericalPassword
    }
    
    0 讨论(0)
  • 2020-12-19 06:59

    As suggested by jisaak, there is no 100% guaranty that the Membership.GeneratePassword Method generates a password that meets the AD complexity requirements.

    That's why I reinvented the wheel:

    Function MakeUp-String([Int]$Size = 8, [Char[]]$CharSets = "ULNS", [Char[]]$Exclude) {
        $Chars = @(); $TokenSet = @()
        If (!$TokenSets) {$Global:TokenSets = @{
            U = [Char[]]'ABCDEFGHIJKLMNOPQRSTUVWXYZ'                                #Upper case
            L = [Char[]]'abcdefghijklmnopqrstuvwxyz'                                #Lower case
            N = [Char[]]'0123456789'                                                #Numerals
            S = [Char[]]'!"#$%&''()*+,-./:;<=>?@[\]^_`{|}~'                         #Symbols
        }}
        $CharSets | ForEach {
            $Tokens = $TokenSets."$_" | ForEach {If ($Exclude -cNotContains $_) {$_}}
            If ($Tokens) {
                $TokensSet += $Tokens
                If ($_ -cle [Char]"Z") {$Chars += $Tokens | Get-Random}             #Character sets defined in upper case are mandatory
            }
        }
        While ($Chars.Count -lt $Size) {$Chars += $TokensSet | Get-Random}
        ($Chars | Sort-Object {Get-Random}) -Join ""                                #Mix the (mandatory) characters and output string
    }; Set-Alias Create-Password MakeUp-String -Description "Generate a random string (password)"
    

    Usage:

    • The Size parameter defines the length of the password.
    • The CharSets parameter define the complexity where the character U, L, N and S stands for Uppercase, Lowercase, Numerals and Symbols. If supplied in lowercase (u, l, n or s) the returned string might contain any of character in the concerned character set, If supplied in uppercase (U, L, N or S) the returned string will contain at least one of the characters in the concerned character set.
    • The Exclude parameter lets you exclude specific characters that might e.g. lead to confusion like an alphanumeric O and a numeric 0 (zero).

    Examples:

    To create a password with a length of 8 characters that might contain any uppercase characters, lowercase characters and numbers:

    Create-Password 8 uln
    

    To create a password with a length of 12 characters that that contains at least one uppercase character, one lowercase character, one number and one symbol and does not contain the characters OLIoli01:

    Create-Password 12 ULNS "OLIoli01"
    

    For the latest Create-Password version, see: https://powersnippets.com/create-password/

    0 讨论(0)
  • 2020-12-19 07:09

    Command to Generate Random passwords by using existing funciton:

    [system.web.security.membership]::GeneratePassword(x,y)
    

    x = Length of the password
    y = Complexity

    General Error:

    Unable to find type [system.web.security.membership]. Make sure that the assembly that contains this type is loaded.

    Solution:

    Run the below command:

    Add-Type -AssemblyName System.web;
    
    0 讨论(0)
  • 2020-12-19 07:14

    You could invoke the Get-Random cmdlet three times, each time with a different input parameter (punc, digit and letters), concat the result strings and shuffle them using another Get-Random invoke:

     (Get-Random -Count 15 -InputObject ([char[]]$yourPassword)) -join ''
    

    However, why do you want to reinvent the wheel? Consider using the following GeneratePassword function:

    [Reflection.Assembly]::LoadWithPartialName("System.Web")
    [System.Web.Security.Membership]::GeneratePassword(15,2)
    

    And to ensure, it contains at least one random number (you already specify the number of symbols):

    do {
       $pwd = [System.Web.Security.Membership]::GeneratePassword(15,2)
    } until ($pwd -match '\d')
    
    0 讨论(0)
提交回复
热议问题