本文介绍了PowerShell - 密码生成器 - 如何始终在字符串中包含数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 PowerShell 脚本,它创建一个 15 位的随机字符串,用作 Active Directory 密码.

I have the following PowerShell script that creates a random string of 15 digits, for use as an Active Directory password.

问题是,这在大多数情况下都很好用,但在某些情况下它不使用数字或符号.我只收到15封信.这不能用作 Active Directory 密码,因为它必须至少包含一个数字或符号.

The trouble is, this works great most of the time, but on some occasions it doesn't use a number or symbol. I just get 15 letters. This is then not usable as an Active Directory password, as it must have at least one number or symbol in it.

$punc = 46..46
$digits = 48..57
$letters = 65..90 + 97..122
$YouShallNotPass = get-random -count 15 `
-input ($punc + $digits + $letters) |
% -begin { $aa = $null } `
-process {$aa += [char]$_} `
-end {$aa}

Write-Host "Password is $YouShallNotPass"

如何修改脚本以使其始终包含至少一个随机数或符号?

How would I amend the script to always have at least one random number or symbol in it?

谢谢.

推荐答案

你可以调用 Get-Random cmdlet 三次,每次使用不同的 input 参数(punc、数字和字母),连接结果字符串并使用另一个 Get-Random 调用:

You could invoke the Get-Random cmdlet three times, each time with a different input parameter (punc, digit and letters), concat the result strings and shuffle them using another Get-Random invoke:

 (Get-Random -Count 15 -InputObject ([char[]]$yourPassword)) -join ''

但是,您为什么要重新发明轮子?考虑使用以下 生成密码函数:

However, why do you want to reinvent the wheel? Consider using the following GeneratePassword function:

[Reflection.Assembly]::LoadWithPartialName("System.Web")
[System.Web.Security.Membership]::GeneratePassword(15,2)

并且为确保,它至少包含一个随机数(您已经指定了符号的数量):

And to ensure, it contains at least one random number (you already specify the number of symbols):

do {
   $pwd = [System.Web.Security.Membership]::GeneratePassword(15,2)
} until ($pwd -match 'd')

这篇关于PowerShell - 密码生成器 - 如何始终在字符串中包含数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-28 19:21
查看更多