PoshCode Archive  Artifact [f91e5f53fc]

Artifact f91e5f53fc438429037e197535cd3e062ed63590ac0eb3cc7471ea71f903dba5:

  • File Get-Password.ps1 — part of check-in [afd0191020] at 2018-06-10 13:42:38 on branch trunk — Another password generating function. This one will always include all the character types you want, and the password will always be random. (user: DollarUnderscore size: 2595)

# encoding: utf-8
# api: powershell
# title: Get-Password
# description: Another password generating function. This one will always include all the character types you want, and the password will always be random.
# version: 0.1
# type: function
# author: DollarUnderscore
# license: CC0
# function: Get-Password
# x-poshcode-id: 4532
# x-archived: 2013-10-25T00:10:52
# x-published: 2013-10-19T11:40:00
#
# Blog post about it is available at:
# http://dollarunderscore.azurewebsites.net/?p=801
#
#========================================================================
# Generated By: Anders Wahlqvist
# Website: DollarUnderscore (http://dollarunderscore.azurewebsites.net)
#========================================================================

function Get-Password
{
    param(
    [int] $PasswordLength = 10)

    # Set how many different character types there are
    $NrOfCharacterTypes=4

    # Make sure the password we are building are at least as long
    # as the character types we want to use.

    if ($PasswordLength -lt $NrOfCharacterTypes) {
        Write-Error "The password must be at least $NrOfCharacterTypes characters long."
        return
    }

    # Set which characters should be used
    $CapitalLetters=For ($a=65;$a –le 90;$a++) { [char][byte]$a }
    $SmallLetters=For ($a=97;$a –le 122;$a++) { [char][byte]$a }
    $Numbers=0..9
    $SpecialCharacters="!","@","#","%","&","?","+","*","=","£","\"

    # Create one array containg all of them
    $AllCharacters=$CapitalLetters+$SmallLetters+$Numbers+$SpecialCharacters

    # Loop until we reach the password length
    for ($CharNr=$NrOfCharacterTypes;$CharNr -le $PasswordLength;$CharNr++) {
        
        # If this is the first run, we should add one of every character type
        if ($CharNr -eq $NrOfCharacterTypes) {
            $CharacterString+=($CapitalLetters | Get-Random)
            $CharacterString+=($SmallLetters | Get-Random)
            $CharacterString+=($Numbers | Get-Random)
            $CharacterString+=($SpecialCharacters | Get-Random)
        }
        # If not, start adding random characters.
        else {
            $CharacterString+=($AllCharacters | Get-Random)
        }
    }

    # Create an char array of the characters
    $TempPasswordArray=$CharacterString.ToString().ToCharArray()

    # Randomize the order of them
    $PasswordToReturn=($TempPasswordArray | Get-Random -Count $TempPasswordArray.length) -join ''

    # Send it back to the pipeline
    Write-Output $PasswordToReturn
}