Napisanie skryptu generującego hasło, to jedno z przyjemniejszych zadań programistycznych. Jest for, są iteracje, jest random. Mniam mniam. Dobra funkcja generująca hasło to jednak coś innego! I właśnie taką udało mi się znaleźć. To co w niej jest najlepsze, to że:
- można określić z jakiej grupy znaków należy generować hasła oraz
- masz gwarancję, że z każdej grupy zostanie wzięty co najmniej jeden znak
Pomyśl teraz (przyjaźnie) o swoim administratorze domeny. Czy nie masz wymogu definiowania hasła o określonej długości ze znakami z określonych grup? Funkcja pochodzi z http://stackoverflow.com/questions/37256154/powershell-password-generator-how-to-always-include-number-in-string (odpowiedź opublikowana przez iRon).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
Function Get-Password { Param( [cmdletbinding()] #Length of the password [Int]$Size = 8, #Charactersets that can be used when password is generated Uppercase, Lowercase, Numbers, Symbols [Char[]]$CharSets = "ULNS", #Characters to skip during password generation [Char[]]$Exclude) #Here final password letters will be saved $Chars = @(); $TokenSet = @() #define table of allowed character lists If (!$TokenSets) { $TokenSets = @{ U = [Char[]]'ABCDEFGHIJKLMNOPQRSTUVWXYZ' #Upper case L = [Char[]]'abcdefghijklmnopqrstuvwxyz' #Lower case N = [Char[]]'0123456789' #Numerals S = [Char[]]'!"#$%&''()*+,-./:;<=>?@[\]^_`{|}~' #Symbols } } #for each set of charactersets allowed (U/L/N/S) foreach ($characterSet in $CharSets) { #take the table of characters in this character set skipping those characters that should be excluded $Tokens = $TokenSets["$characterSet"] | ForEach {If ($Exclude -cNotContains $_) {$_}} #if still some characters left (should be usually the case) If ($Tokens) { #generate the table of only the valid characters $TokensSet += $Tokens #as we guarantee that at least one character of each character set will #be present in the password, we take here one character from the list $Chars += $Tokens | Get-Random } } #now we get random number of characters from the approved list While ($Chars.Count -lt $Size) { $Chars += $TokensSet | Get-Random } #finally we return the result - the list of charaters needs to be converted to a string ($Chars | Sort-Object {Get-Random}) -Join "" }; |
Oto przykłady wywołania tej funkcji:
1 |
Get-Password -Size 10 |
1 |
Get-Password -size 20 -CharSets 'ULN' |