Quick Script Share: Get-RandomPW – Create Random Passwords

I had a need to repeatedly create random passwords of varying lengths. To satisfy this need, I wrote the following basic script.

On line 1, you can see I named my function Get-RandomPW which I did because I like following the standard Verb-Noun naming scheme that PowerShell functions and cmdlets are supposed to follow. On lines 3 through 6, I’m declaring my only parameter, $Length. $Length is an integer which will represent the length of the password we want. By default, I create a 16 character password.

On line 7, $arrChars is declared and assigned the value of all the valid characters for my password. I list all the characters in one big string and convert to a Char array because it’s easier to look at and manage, in my opinion.

On line 8, I finally build the password. For all the numbers between 1 and $Length, I’m getting a random item from $arrChars. The result of that is an array, so I use the -join method to create a string from the array. On line 9, I return the password I built.

Here’s what the script looks like in action.