Boost your shell with reusable code stripped to its essentials


As there is no 100% guaranty that the Membership.GeneratePassword Method generates a password that meets the AD complexity requirements, I create a small cmdlet to generate random strings according to a certain complexity:


Function Create-String{                                         # https://powersnippets.com/create-password/
    [CmdletBinding()]Param (                                    # Version 01.01.00, by iRon
        [Int]$Size = 8, [Char[]]$Complexity = "ULNS", [Char[]]$Exclude
    $AllTokens = @(); $Chars = @(); $TokenSets = @{
        LowerCase = [Char[]]'abcdefghijklmnopqrstuvwxyz'
        Numbers   = [Char[]]'0123456789'
        Symbols   = [Char[]]'!"#$%&''()*+,-./:;<=>?@[\]^_`{|}~'
    $TokenSets.Keys | Where {$Complexity -Contains $_[0]} | ForEach {
        $TokenSet = $TokenSets.$_ | Where {$Exclude -cNotContains $_} | ForEach {$_}
        If ($_[0] -cle "Z") {$Chars += $TokenSet | Get-Random}    #Character sets defined in uppercase are mandatory
        $AllTokens += $TokenSet
    While ($Chars.Count -lt $Size) {$Chars += $AllTokens | Get-Random}
    ($Chars | Sort-Object {Get-Random}) -Join ""                #Mix the (mandatory) characters and output string
}; Set-Alias Create-Password Create-String -Description "Generate a random string (password)"


Create-String  [[-Size]  <int>]  [[-Complexity]  <[U|u]|[L|l]|[N|n]|[S|s]>]  [[-Exclude]  <char[]>]


[[-Size] <int>]
The size of the password.

[[-Complexity] <[U|u]|[L|l]|[N|n]|[S|s]>]
The complexity of the password where the characters U, L, N and S refer to the character sets: Uppercase, Lowercase, Numerals and Symbols. If supplied in lowercase (u, l, n or s) the returned password 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.

[[-Exclude] <char[]>]
A list with unwanted characters to exclude from the password.


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

Create-String 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 O, L, I, o, l, i, 0 or 1:

Create-String 12  ULNS  "OLIoli01"

The Create-Password cmdlet was originally published at StackOverflow

Last updated on 29 Jun 2020
Published on 6 Nov 2017