Skip to content

Instantly share code, notes, and snippets.

@joshooaj
Forked from steviecoaster/New-RandomPass.ps1
Last active December 10, 2024 23:31
Show Gist options
  • Save joshooaj/2c6adad43f3fd6c92bb88f6ad5067718 to your computer and use it in GitHub Desktop.
Save joshooaj/2c6adad43f3fd6c92bb88f6ad5067718 to your computer and use it in GitHub Desktop.
Cross platform password generator
function New-RandomPass {
<#
.Synopsis
Generates and returns a suitably secure password
.EXAMPLE
New-RandomPass
Returns a random password as a SecureString object
.EXAMPLE
New-RandomPass -Length 128
Returns a random password whose length is 128 characters as a SecureStringObject
.EXAMPLE
New-RandomPass -AsPlainText
Returns a random password as plain text
#>
[CmdletBinding()]
[OutputType([System.Security.SecureString])]
param(
[Parameter()]
[ValidateRange(1, 128)]
[int]$Length = 64,
[Parameter()]
[char[]]$AvailableCharacters = @(
# Specifically excluding $, `, ;, #, etc such that pasting
# passwords into support scripts will be more predictable.
'!%()*+,-./<=>?@[\]^_'
48..57 # 0-9
65..90 # A-Z
97..122 # a-z
).ForEach{ [char[]]$_ },
[Parameter()]
[Switch]
$AsPlainText
)
end {
$NewPassword = [System.Security.SecureString]::new()
$cryptoRandom = [System.Security.Cryptography.RandomNumberGenerator]::Create()
$bytes = [byte[]]::new(2)
while ($NewPassword.Length -lt $Length) {
$cryptoRandom.GetBytes($bytes)
$index = [bitconverter]::ToUInt16($bytes, 0) % $AvailableCharacters.Count
$NewPassword.AppendChar($AvailableCharacters[$index])
}
if ($AsPlainText) {
[System.Net.NetworkCredential]::new($null, $NewPassword).Password
} else {
$NewPassword
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment