TXServerAnalyst
TXServerAnalyst

Reputation: 11

Automatically Adding a Number to variable in Powershell

I have looked at some sites online and browsed a few answers here and I have had no luck with my question.

I have a PowerShell script to automate account creations using information entered in the host. My question is this, how can I set my script to automatically add a number at the end of the submitted data if it already exists? Code block is below:

$Username = Read-host "Enter Desired Username"

#Test

IF(!(Get-ADUser -Identity $Username))
{ Write-Host "$username exists. Adding number.
  HERE IS THE CODE I AM LOOKING FOR TO TAKE THE $Username and automatically add the number at the end.
}

If this was already answered, please send me the link and I'll mark this as answered but if not, any suggestions would be great.

Thanks!

Upvotes: 1

Views: 1051

Answers (3)

Mark Wragg
Mark Wragg

Reputation: 23385

To supplement the other answer, you could also do something like this to determine the next available username:

$Username = Read-Host -Prompt 'Enter desired username'

$TestUsername = $Username

$i = 1

While (Get-ADUser -Identity $TestUsername)
{
    Write-Warning "$TestUsername is taken"
    $TestUsername = $Username + $i++
}

"The next available username is $TestUsername"

Within the loop the ++ operator is used to increment the counter variable $i and appends that to the original username each time the loop repeats. Note that it is appended first then incremented second, so we start at 1.

Upvotes: 2

Chenry Lee
Chenry Lee

Reputation: 380

I've written such a script. My logic is:

  1. Before creating an account, query this account firstly
  2. If the account exists, suffix a 2 digits number (from 01, format by "{0:d2}" -f
  3. Query the suffixed account, repeat step 1 and 2, till the account doesn't exist (use recursive function).

It's the code:

$seq = 1
Function Check-Existing {
    param(
        [Parameter(Mandatory=$true)]
        [string]$Account
    )

    while (Get-ADUser $Account){
        $suffix = "{0:d2}" -f $seq
        $Account = $Account + $suffix
        $seq++
        return $Account
    }

    Check-Existing -Account $Account
}

(I'll double check the code on Monday)

Upvotes: 1

Maximilian Burszley
Maximilian Burszley

Reputation: 19684

Since this script isn't being automatically run and there is user input, I would suggest just re-prompting the user if the name is taken:

Do
{
    $Username = Read-Host -Prompt 'Enter desired username'
} While (Get-ADUser -Identity $Username)

Alternatively:

$Username = Read-Host -Prompt 'Enter desired username'
While (Get-ADUser -Identity $Username)
{
    "Username '$Username' taken!"
    $Username = Read-Host -Prompt 'Enter desired username'
}

Upvotes: 2

Related Questions