【问题标题】:PowerShell Username Generator - Add to File/Check AgainstPowerShell 用户名生成器 - 添加到文件/检查
【发布时间】:2022-10-21 06:51:51
【问题描述】:

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

Get-Random -Minimum 1000 -Maximum 10000

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

流程应该是:

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

【问题讨论】:

  • 将文件的所有行加载为哈希表中的键,值可以设置为任何值,例如 $true(但以后无需检查该值)。 do{ 生成新密钥 } while ( hashtable containskey ),将密钥添加到 hashtable,用 hashtable 中的所有密钥覆盖文件。
  • 我会... [1] 检查以您的 3 个字符开头的任何用户名。 [2] 找到使用过的数字。 [3] 创建一个最小..最大范围。 [4] 删除使用过的数字。 [5] 从剩余的数字范围中抓取一个随机数。

标签: powershell file random


【解决方案1】:

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

$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

【讨论】:

  • 这可行,但我将如何编辑代码以删除 R Y A 的输出?我只需要它来输出随机的 4 位数字吗?
  • 你的规格很奇怪,但我编辑了我的答案,没有那个输出
【解决方案2】:

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

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

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 = "$PSScriptRootUsernames.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)$')

【讨论】:

  • 所以这会生成一个随机的 4 位数字,如果该数字已经存在,它会跳过并生成一个新数字吗?
  • @Psychadelic23,是的。 do {$NewUserName = GenUserName $UserPrefix} while ($Usernames.ContainsKey($NewUserName)) 将重复,直到在 $Usernames 中找不到 $NewUserName。每次重复时,$NewUserName 从 GenUserName 获取新用户名。 GenUserName 调用 RandomDigits,创建一个新用户。我通过将"$Prefix$(RandomDigits 4)" 更改为"$Prefix$(RandomDigits 1)" 对此进行了测试,这创建了只有1 位数字的用户名。然后重复输入相同的 3 个字母,产生所有 10 个可能的用户名,然后陷入无限循环 - 因为它找不到未使用的名称。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-20
  • 1970-01-01
  • 2019-01-28
  • 1970-01-01
  • 2018-01-19
  • 1970-01-01
相关资源
最近更新 更多