Skip to content

Instantly share code, notes, and snippets.

@Sarafian
Last active May 2, 2017 09:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sarafian/2ce5d18d33bf98ae758f2b6db9a59823 to your computer and use it in GitHub Desktop.
Save Sarafian/2ce5d18d33bf98ae758f2b6db9a59823 to your computer and use it in GitHub Desktop.
Generate new random password with PowerShell
function New-RandomPassword
{
param(
[Parameter(Mandatory=$false)]
[int]$Length=8
)
begin {
}
process {
$numericChars=@(
'0123456789'.ToCharArray()
)
$upperCaseChars=@(
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.ToCharArray()
)
$lowerCaseChars=@(
'abcdefghijklmnopqrstuvwxyz'.ToCharArray()
)
$specialChars=@(
"{|}/>(<&*,!@;+#[]\~.):?%$'`"".ToCharArray()
)
$allChars=@(
$numericChars
$upperCaseChars
$lowerCaseChars
$specialChars
)
# Make sure one character of each group will exist in the password
$randomChars=@(
$numericChars | Get-Random
$upperCaseChars | Get-Random
$lowerCaseChars | Get-Random
$specialChars | Get-Random
)
# Add random character from all groups
$randomChars+=$allChars | Get-Random -Count ($Length - $randomChars.Length)
# Randomize and stringify
(-join ($randomChars | Get-Random -Count $randomChars.Length)).ToString()
}
end {
}
}
@Sarafian
Copy link
Author

Sarafian commented May 2, 2017

Example 1

PS C:\> New-RandomPassword
NHOZ1&k>

Example 2

PS C:\> New-RandomPassword -MinumumLength 16
yEeqWT),MK0&|x{<

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment