In my last post I showed you a function to generate secure and complex passwords. This time I have written a small function you can use to test password strength similar to the strength bar you sometimes see in password fields on websites.
The output is a simple string telling you the strength of the password.
| function Test-PasswordStrength { | |
| <# | |
| .SYNOPSIS | |
| Test password strength. | |
| .DESCRIPTION | |
| This functions lets input a password to test it strength. | |
| .EXAMPLE | |
| Test-PasswordStrength 'MyCoolPassword' | |
| .NOTES | |
| Based on code example from https://social.msdn.microsoft.com/Forums/vstudio/en-US/5e3f27d2-49af-410a-85a2-3c47e3f77fb1/how-to-check-for-password-strength?forum=csharpgeneral | |
| Author: Øyvind Kallstad | |
| Date: 24.09.2015 | |
| Version: 1.0 | |
| .OUTPUTS | |
| System.String | |
| .LINK | |
| https://communary.wordpress.com/ | |
| #> | |
| [CmdletBinding()] | |
| param ( | |
| # The password to test | |
| [Parameter(Position = 0, Mandatory = $true, ValueFromPipeline = $true)] | |
| [ValidateNotNullOrEmpty()] | |
| [string] $Password | |
| ) | |
| $score = 0 | |
| if ($Password.Length -lt 5) { | |
| Write-Verbose 'Password length is less than 5 characters.' | |
| Write-Output 'Very Weak' | |
| break | |
| } | |
| if ($Password.Length -ge 8) { | |
| Write-Verbose 'Password length is equal to or greater than 8 characters. Added 1 to password score.' | |
| $score++ | |
| } | |
| if ($Password.Length -ge 12) { | |
| Write-Verbose 'Password length is equal to or greater than 12 characters. Added 1 to password score.' | |
| $score++ | |
| } | |
| if ([regex]::IsMatch($Password, '\d+')) { | |
| Write-Verbose 'Password contains numbers. Added 1 to password score.' | |
| $score++ | |
| } | |
| if ([regex]::IsMatch($Password, '[a-z]+')) { | |
| Write-Verbose 'Password lowercase letters. Added 1 to password score.' | |
| $score++ | |
| } | |
| if ([regex]::IsMatch($Password, '[A-Z]+')) { | |
| Write-Verbose 'Password uppercase letters. Added 1 to password score.' | |
| $score++ | |
| } | |
| if ([regex]::IsMatch($Password, '[!@#$%^&*?_~-£(){},]+')) { | |
| Write-Verbose 'Password symbols. Added 1 to password score.' | |
| $score++ | |
| } | |
| switch ($score) { | |
| 1 { $passwordScore = 'Very Weak' } | |
| 2 { $passwordScore = 'Weak' } | |
| 3 { $passwordScore = 'Medium' } | |
| 4 { $passwordScore = 'Strong' } | |
| 5 { $passwordScore = 'Strong' } | |
| 6 { $passwordScore = 'Very Strong' } | |
| } | |
| Write-Output $passwordScore | |
| } |