Public/New-Password.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
Function New-Password() {
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute(
        "PSUseDeclaredVarsMoreThanAssignments", 
        "Alphabet", 
        Justification = "Parsing error in script analyzer"
    )]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute(
        "PSUseShouldProcessForStateChangingFunctions", 
        "", 
        Justification = "Object is only created in memory"
    )]
    <#
    .SYNOPSIS
    Generates a new password

    .DESCRIPTION
    The password is based on an alphabet

    .PARAMETER Length
    Length of the password

    .PARAMETER Alphabet
    Alphabet used for generating the password

    .EXAMPLE
    New-Password -Length 12

    .EXAMPLE
    New-Password -Length 12 -Alphabet "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray()
    #>

    [CmdletBinding()]
    [OutputType([string])]
    Param(
        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [int]
        $Length=10
        ,
        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [string[]]
        $Alphabet
    )

    if (-Not $Alphabet) {
        $Alphabet = $null
        40..126 + 33 + 35..38 | ForEach-Object {
            $Alphabet += ,[char][byte]$_
        }
    }

    $TempPassword = ''
    For ($i = 1; $i -le $Length; $i++) {
        $TempPassword += ($Alphabet | Get-Random)
    }

    return $TempPassword
}