I looked around at examples of generating ‘random’ passwords with PS, and while I could probably copy-paste something, a lot of it seems long-winded and I wanted to try it myself. I came up with this, which offers the control and requirements I am after…
Well, you’re appending a string together, so that’s what you get. Sort-Object can’t “sort” a single string.
I wonder if you started by declaring
$pass = @()
Meaning, $pass is an array of characters. You’d then be adding items to an array - well, a collection, technically - and Sort-Object can operate on that. You’d probably have to run the final result through Out-String to turn it into a single string.
Hi Don, again, thank you for this great community and all of your efforts here.
I am not sure if this is exactly what you meant, but I do have all of the characters in an array (I checked, GetType(), and $pass[0…7], etc), and I have that piped to Sort-Object {Get-Random}, and it is what I need it to be…
Hi Dirk,
Nice example. The only draw back I see there is you don’t get repeating characters which eliminates some of the complexity, and would be necessary if, for example, they wanted 5 special characters from the list of 3 possibilities.
There is one aspect that I’m not understanding how it works. I can see that it obviously does work, but I would like to understand why.
| sort {Get-Random}
What is this doing? How does Sort-Object interact with the Curly Braces and Get-Random here? I can’t find any documentation on it.
Slight modification to your code so you can get repeat characters in each category
Hi Curtis,
good thinking.
The way this works is, that the result of the expression within the scriptblock is used to rank the indiviual elements of the collection. Since Get-Random is used, it results in a random order. This makes Sort-Object really powerful.
I’ve written a blog post (Sort data using a custom list in PowerShell). Here are some more examples on how this can be used:
#Descending (not the best way of doing it)
1..5 | sort { -$_ }
"--"
#Even after odd
1..5 | sort { $_ % 2 }
#numberwords
"--"
$numberWords="three","one","two","four"
$numberWords=$numberWords*10
$customList="one","two","three","four"
$numberWords | sort { $customList.IndexOf($_) }
Ok, I think I get it, since get-random generates a random large number for each object that is piped in, the result is the list being sorted numerically by the number randomly generated by get-random. This is intriguing. I’m gonna have to play with it a little more. Thanks for sharing the knowledge.