Saturday, February 24, 2018

Count Number of Unique Passwords Powershell Hashtables

I'm on a password kick lately.  I read about hash tables in Powershell.  They are so cool.  So, I wrote a script that counts the number of unique passwords in a text file that contains usernames and passwords.  It also sorts the passwords from the most used to the least used, using the GetEnumerator method and Sort-Object.  Keep in mind everyone, I'm still new to Powershell.  Someone may have already done this, or there may be more efficient methods.  This is what I've learned to this point in time.

#Make a hash table to hold the passwords and count.
$passwordscount = @{}

#Make a variable to hold each of the passwords
$password

#Get the content of the passwords file and add it to a list
$passwordslist = Get-Content plain.txt

#Tell powershell the column number of the plain.txt file that you want in the hash table.
#The computer counts from 0, so it will be one less than the column you want.
#For example, plain.txt has a username and password separated by a column.
#You want column 1.  Column 0 is the username.

$passwordscolumnnumber = 1

#For each password in the passwords list, do the following
ForEach($password in $passwordslist){
    #Split each line of the plain.txt file into an array, splitting at the colon
    #The username is element 0, the password is element 1
    $passwordsarray = $password.split(':')

    #separate these passwords from the username and count them
    $passwordfield = $passwordsarray[$passwordcolumnnumber];

    #If this is the first occurrence of a password, add it to the hash table and put 1 in the count
    If ($passwordscount[$passwordfield -eq $null]{
        $passwordscount[$passwordfield] = 1
    }
    Else{
    #if a password has already been seen, add 1 to it's count
        $passwordscount[passwordfield]++
    }
}

$passwordscount.GetEnumerator() | Sort-Object -Property Value | Out-File passwordscount.txt


No comments:

Post a Comment