如何使用随机选择的数组创建哈希表?

时间:2014-03-15 16:16:38

标签: powershell hashtable

我有6个用户,需要使用小写字母,数字和符号组合制作6个字符的密码,但我不知道接下来该做什么。 这就是我到目前为止所做的:

$=i; $++; $ -le 6
$Lowercase1: [a-z]
$Uppercase1: [A-Z]
$Digit: [0-9]
$Lowercase2: [a-z]
$Symbol: [!@#$%^&*?+]
$Uppercase2: [A-Z]

然后我在一个文本文件中有我的6个用户,我需要在其中创建一个哈希表,如下所示:

Mary Jane               fY5s&A

我不知道如何把它放在那种格式中。如果你能帮助我,我将不胜感激。

我在这里制作了密码生成器。那么我现在如何将它放到get-password

$Lowercase= @("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z") | Get-Random 
$Uppercase= @("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z") | Get-Random
$Digit= @(0..9) | Get-Random
$Lowercase2= @("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z") | Get-Random
$Symbol= @("!","@","#","$","%","^","&","*","?","+") | Get-Random
$Uppercase2= @("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z")| Get-Random

#Exercise 2:  Generating a Random Password
$Password= $Lowercase + $Uppercase + $Digit + $Lowercase2 + $Symbol + $Uppercase2

2 个答案:

答案 0 :(得分:2)

假设你实际上有一些工作代码来生成密码(你发布的不是),如果你把它放到一个叫做的函数中,例如Get-Password然后创建该哈希表可能如下所示:

$PasswordHash = @{}

Get-Content c:\somedir\users.txt |
 foreach {
  $PasswordHash[$_] = Get-Password
 }

答案 1 :(得分:0)

就个人而言,我会使用.Net framework-methods生成密码,而不是创建数组并运行多个get-random命令。 .Net框架已经有GeneratePassword - 方法,您可以调整以满足您的需求。像这样:

function Get-Password {
    #Load System.Web assembly (this contains the password-method).
    [Reflection.Assembly]::LoadWithPartialName("System.Web") | Out-Null

    #Get a random capital letter
    $replacement = [Convert]::ToChar((Get-Random -Minimum 65 -Maximum 90))

    #Generate password replace characters that aren't allowed with the $replacement character
    [System.Web.Security.Membership]::GeneratePassword(6,0) -replace '[^a-zA-Z0-9!@#$%^&*?+]', $replacement
}

#Create hashtable
$ht = @{}

#Read username and fill in hashtable
Get-Content .\users.txt | ForEach-Object {
  $ht[$_] = Get-Password
}