为了娱乐,我决定创建一个函数,该函数将根据用户决定的数量生成一些随机密码。我正在使用Begin和Process块来运行脚本。 Begin块具有$ characterPool变量,其中字母数字和特殊字符为潜在字符。 Process块询问用户需要多少个密码,并创建那么多随机的12个字符的密码。当我第一次创建函数时,它工作正常。现在,无论我请求多少个密码,都只会创建两个,然后重新提出问题。然后,使用空字符串按Enter或添加另一个数字将导致输出一个密码。
Begin
{
$characterPool = "!@#$%^&*0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz".ToCharArray()
}
Process
{
[pscustomobject]@{
Password = -join ($characterPool | Get-Random -Count 12)
}
$counter = Read-Host -Prompt "How many passwords do ya want, buddy?"
1..$counter | New-RandomPassword
}
我希望这会生成我要求的密码数量。不会产生任何错误,它只会显示如下:
Begin
{
$characterPool = "!@#$%^&*0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz".ToCharArray()
}
Process
{
[pscustomobject]@{
Password = -join ($characterPool | Get-Random -Count 12)
}
$counter = Read-Host -Prompt "How many passwords do ya want, buddy?"
1..$counter | New-RandomPassword
}
How many passwords do ya want, buddy?: 5
Password
--------
1z@p8Jgl52yU
1#K8z2@iA!&o
How many passwords do ya want, buddy?:
Pw!C#d2xTjMu
How many passwords do ya want, buddy?:
fo*Oca9HbRQr
How many passwords do ya want, buddy?:
omzCRpwqdOfM
How many passwords do ya want, buddy?:
u5lMN!kjhzfe
How many passwords do ya want, buddy?: 6
vLaxHq945K$D
How many passwords do ya want, buddy?:
答案 0 :(得分:2)
将Read-Host
提示功能移至开始并将密码生成逻辑移入循环:
function New-RandomPassword {
param()
[int]$counter = Read-Host -Prompt "How many passwords do ya want, buddy?"
$characterPool = "!@#$%^&*0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz".ToCharArray()
$i = 0;
while($i++ -lt $counter)
{
[pscustomobject]@{
Password = -join ($characterPool | Get-Random -Count 12)
}
}
}
这样,您将不必递归调用函数。
我个人将$counter
变量转换为参数,然后在脚本中提示用户,该脚本在内部调用 New-RandomPassword
function New-RandomPassword {
param(
[ValidateRange(1,500)]
[int]$Count
)
$characterPool = "!@#$%^&*0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz".ToCharArray()
$i = 0;
while($i++ -lt $count)
{
[pscustomobject]@{
Password = -join ($characterPool | Get-Random -Count 12)
}
}
}
与mklement0 pointed out一样,您也可以使用Read-Host
调用将表达式指定为参数的默认值:
param(
[ValidateRange(1,500)]
[int]$Count = $(Read-Host 'How many passwords do ya want, buddy?')
)
我个人认为这是一种反模式,宁愿坚持默认为1
或标记参数Mandatory
:
# If the caller omits the argument, 1 password is returned
param(
[ValidateRange(1,500)]
[int]$Count = 1
)
或
# Caller _must_ supply a parameter argument (the default console host will prompt the user if not, but depends on the host application)
param(
[Parameter(Mandatory = $true)]
[ValidateRange(1,500)]
[int]$Count
)