脚本
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
| function New-Password { param ( [Parameter()][ValidateRange(8, 128)][int]$Length = 16, [Parameter()][switch]$NoUppercase, [Parameter()][switch]$NoLowercase, [Parameter()][switch]$NoNumbers, [Parameter()][switch]$NoSymbols )
$chars = @( [PSCustomObject]@{Name = 'NoUppercase'; Number = 65..90} [PSCustomObject]@{Name = 'NoLowercase'; Number = 97..122} [PSCustomObject]@{Name = 'NoNumbers'; Number = 48..57} [PSCustomObject]@{Name = 'NoSymbols'; Number = 33..47 + 58..64 + 94..96 + 123..126} )
$switches = $MyInvocation.MyCommand.Parameters.Keys | Where-Object {$_ -match 'No'} $selected = $PSBoundParameters.Keys | Where-Object {$_ -match 'No'} $luckySwitch = $switches | Where-Object {$_ -notin $selected} | Get-Random
if ($selected.Count -eq 4) {throw 'Please select at least one character type'}
$divisor = 4 - $selected.Count $quotient = [Math]::Floor($Length / $divisor) $remainder = $Length % $divisor
$randomChars = foreach ($char in $chars) { if ($char.Name -notin $selected) { $count = if ($char.Name -eq $luckySwitch) {$quotient + $remainder} else {$quotient} 1..$count | ForEach-Object {Get-Random -InputObject $char.Number} } }
-join ($randomChars | ForEach-Object {[char]$_} | Sort-Object {Get-Random}) }
|
- 此脚本适用于 PowerShell 5.1 及更高版本。
- 此脚本基于 Functions 编写,保存到本地后可通过 Dot Sourcing 进行调用。
语法
1
| New-Password [[-Length] <int>] [-NoUppercase] [-NoLowercase] [-NoNumbers] [-NoSymbols] [<CommonParameters>]
|
描述
New-Password 命令可生成长度 8 到 128,四种字符类型(大写、小写、数字、符号)随意组合的随机密码。默认情况下,New-Password 命令生成长度 16,包含所有字符类型的随机密码。
示例