PowerShell 用户名生成器 - 添加到 File/Check 反对

PowerShell Username Generator - Add to File/Check Against

我正在这样创建用户名:名字的前 3 个字母,然后是 4 个随机生成的数字。瑞安·史密斯 = RYA4859。我从这个 PowerShell 命令中获取随机数:

获取-随机-最小1000-最大10000

我需要知道如何创建一个脚本,在用户名生成后将其添加到 .txt 文件中。我还希望脚本首先检查 .txt 文件以查看随机生成的数字是否已经存在,如果存在,则生成一个不存在的新 4 位数字,然后将其添加到 .txt 文件中。

流程应该是:

生成随机的 4 位数字 检查 txt 文件是否存在数字 如果是 - 生成新号码 如果没有 - 附加文件并将生成的数字添加到文件

您想 运行 一个 do...until 循环 运行s 直到随机生成的数字不存在于您的文本文件中

$file = "C:\users.txt"
$userId = "RYA"

# get the contents of your text file
$existingUserList = Get-Content $file

do
{
    $userNumber = Get-Random -Minimum 1000 -Maximum 10000

    # remove all alpha characters in the file, so only an array of numbers remains
    $userListReplaced = $existingUserList -replace "[^0-9]" , ''

# the loop runs until the randomly generated number is not in the array of numbers
} until (-not ($userNumber -in $userListReplaced))

# concatenates your user name with the random number
$user = $userId + $userNumber

# appends the concatenated username into the text file
$user | Out-File -FilePath $file -Append

没有 3 个字符前缀

$file = "C:\users.txt"

# get the contents of your text file
$existingUserList = Get-Content $file

do
{
    $userNumber = Get-Random -Minimum 1000 -Maximum 10000

    # remove all alpha characters in the file, so only an array of numbers remains
    $userListReplaced = $existingUserList -replace "[^0-9]" , ''

# the loop runs until the randomly generated number is not in the array of numbers
} until (-not ($userNumber -in $userListReplaced))
    
# appends the concatenated username into the text file
$userNumber| Out-File -FilePath $file -Append

注意: 与在未排序的数组中查找匹配元素相比,哈希表通常查找键的时间更短。这种性能差异随着元素数量的增加而增加。虽然对已排序数组进行二分查找在性能上可能更接近,但排序过程本身可能会严重影响性能并增加代码的复杂性。

问题评论中描述的代码版本与以下代码之间的主要区别在于,我将新用户名附加到文件而不是覆盖文件,并添加了一个在接近尾声时循环重复询问代码是否应该继续。

function RandomDigits {
    [CmdletBinding()]
    param (
        [Parameter()]
        [int]$DigitCount = 2
    )
    $RandString = [string](Get-Random -Minimum 100000 -Maximum 10000000)
    $RandString.Substring($RandString.Length-$DigitCount)
}
function GenUserName {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true, Position = 0)]
        [string]$Prefix
    )
    "$Prefix$(RandomDigits 4)"
}
function ReadAndMatchRegex {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true, Position = 0)]
        [string]$Regex,
        [Parameter(Mandatory = $true, Position = 1)]
        [string]$Prompt,
        [Parameter(Mandatory = $false, Position = 2)]
        [string]$ErrMsg = "Incorrect, please enter needed info (Type 'exit' to exit)."
    )
    $FirstPass = $true
    do {
        if (-not $FirstPass) {
            Write-Host $ErrMsg -ForegroundColor Red
            Write-Host
        }
        $ReadText = Read-Host -Prompt $Prompt
        $ReadText = $ReadText.ToUpper()
        if($ReadText -eq 'exit') {exit}
        $FirstPass = $false
    } until ($ReadText -match $Regex)
    $ReadText
}
$Usernames = @{}
$UsernameFile = "$PSScriptRoot\Usernames.txt"
if(Test-Path -Path $UsernameFile -PathType Leaf) { 
    foreach($line in Get-Content $UsernameFile) { $Usernames[$Line]=$true }
}
do {
    Write-Host
    $UserPrefix = ReadAndMatchRegex '^[A-Z]{3}$' "Please enter 3 letters for user's ID"
    do {
        $NewUserName = GenUserName $UserPrefix
    } while ($Usernames.ContainsKey($NewUserName))
    $NewUserName | Out-File $UsernameFile -Append
    $UserNames[$NewUserName]=$true
    $UserNames.Keys
    $Continue = ReadAndMatchRegex '^(Y|y|YES|yes|Yes|N|n|NO|no|No)$' 'Continue?[Y/N]'
} while ($Continue -match '^(Y|y|YES|yes|Yes)$')