我有脚本(我从论坛上调整过)读取包含用户名的文本文件。
这将生成一个 9 个字符的随机密码并通过 PowerShell 输出密码:
$ListOfUsers = Get-Content C:\temp\list.txt
foreach ($user in $ListOfUsers) {
#Generate a 9-character random password
$Password = -join ((33..126) | Get-Random -Count 9 | ForEach-Object { [char]$_ })
#Convert the password to secure string
$Pass = ConvertTo-SecureString $Password -AsPlainText -Force
#Reset the account password
Set-ADAccountPassword $user -NewPassword $Pass -Reset
#Display userid and password values
Write-Host $user, $Password
}
由于它显示的密码包含特殊字符 - 这会给访问我们网络上特殊设备的某些用户带来问题,我不得不在 AD 中为这些用户手动设置随机密码。
我想知道是否可以定义一个仅包含字母(小写和大写)和数字的随机密码?
或
我可以提供一个文本文件,每行都有密码,以便 PowerShell 为每个用户设置密码吗?
您可以使用下面的辅助函数来生成带或不带特殊字符的密码:
function New-Password {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
[ValidateRange(8, 128)]
[int]$TotalLength = 10,
[int]$LowerAlpha = 3,
[int]$UpperAlpha = 2,
[int]$Digits = 3,
[int]$Symbols = 2
)
# check if the given parameters are => 0 and <= $TotalLength
$LowerAlpha = [math]::Max(0,[math]::Min($LowerAlpha, $TotalLength))
$UpperAlpha = [math]::Max(0,[math]::Min($UpperAlpha, $TotalLength))
$Digits = [math]::Max(0,[math]::Min($Digits, $TotalLength))
$Symbols = [math]::Max(0,[math]::Min($Symbols, $TotalLength))
if ($TotalLength - ($LowerAlpha + $UpperAlpha + $Digits + $Symbols) -lt 0) {
throw "Too many alphas, digits or symbols to fit the total password length"
}
$list = [System.Collections.Generic.List[char]]::new()
if ($LowerAlpha) { $list.AddRange([char[]]([char[]]'abcdefghijklmnopqrstuvwxyz' | Get-Random -Count $LowerAlpha)) }
if ($UpperAlpha) { $list.AddRange([char[]]([char[]]'ABCDEFGHIJKLMNOPQRSTUVWXYZ' | Get-Random -Count $UpperAlpha)) }
if ($Digits) { $list.AddRange([char[]]([char[]]'0123456789' | Get-Random -Count $Digits)) }
if ($Symbols) { $list.AddRange([char[]]([char[]]'!@#$%^&*()_-+=[{]};:<>|./?~' | Get-Random -Count $Symbols)) }
($list | Sort-Object {Get-Random}) -join ''
}
用法:
将上面的函数粘贴到您的脚本之上,然后您的代码将变为:
$ListOfUsers = Get-Content C:\temp\list.txt
$result = foreach ($user in $ListOfUsers) {
#Generate a 9-character random password
$Password = New-Password -TotalLength 9 -Symbols 0
#Convert the password to secure string
$Pass = ConvertTo-SecureString $Password -AsPlainText -Force
#Reset the account password
Set-ADAccountPassword $user -NewPassword $Pass -Reset
#Display userid and password values
#Write-Host $user, $Password
# or better yet, output the newly set passwords as PsCustomObject to use in a csv file
[PsCustomObject]@{User = $user; Password = $Password}
}
# show on screen
$result | Format-Table -AutoSize
# write to CSV file you can open in Excel by double-clicking it
$result | Export-Csv -Path 'C:\temp\NewPasswords.csv' -NoTypeInformation -UseCulture