Q: List all AD computer account & create a new one based on the last entry

Hi NG,

I’m trying something that I thought of to be simple :slight_smile: but somehow issn’t to me.

I need to create new AD computer accounts based on the last account found in the AD.
In our company we have a strikt naming convention which should make it easy to create new accounts based on the last one.

Our naming schema is somehting like: USLAXDT123456

The last 6 digits are running numbers. So basically I only need to iterate this by 1.

My first approach would be to select -last 1 of the AD acccounts.
Split the name from the number. ($var = USLAXDT123456.remove(0,7)
Iterate the number… somehow maybe like this:
$var += 1

Then bring the string part back together with the number.

Is there an easier way to do that?

Regards

Christian

Hi Christian,

Think you’re heading on the right lines. For splitting the number from the letters, you can also use .substring, and for working out the next number, Measure-Object with the -maximum parameter is your friend.

Happy to give an example if you’d like. :slight_smile:

Here’s one way to do it. The match is to make sure you only get relevant computernames. The while-loop adds zeros if neccessary.

$numbers = Get-ADComputer -Filter * | ? {$_.name -match ‘^USLAXDT[0-9]{6}$’} | Select-Object @{n = ‘number’; e = {int}} | Select-Object -expandproperty number | Sort-Object
$newNumber = [string]($numbers | Measure-Object -Maximum).Maximum
while ($newNumber.Length -lt 6) {$newNumber = “0$newNumber”}
$newName = “USLAXDT$newNumber”

Hi again,

@ Tim : Tim thx for your input. I used substring to get only the number that I need

@ Thomas: I got a question about the filter --> $_.name -match ‘^USLAXDT[0-9]{6}$’

What is the $ sign @ the end needed for? With or without I seem to get the same result.

I solved it like this now:

extract the OU from the entry in list

$strOU = $entry | select-object -ExpandProperty OU

Get the AD object with the highest count

$lastADaccount = get-adcomputer -filter * -SearchBase $strOU | where-object {$_.name -match “USLAXDT[0-9]{6}”} | select-object -ExpandProperty name -last 1

split the number from the chars

$strnumber = $lastADaccount.Substring(7)

convert string to integer

$intnumber = [int] $strnumber

interate by one

$intnumber++

combine new AD computer account name

“USLAXDT” + $intnumber

regards

Christian

^ and $ matches start and end of string

I’m not sure selecting the last 1 will always return the newest computer account. I would look for the maximum number in existing names instead.

Hi again Thomas,

you’re correct :slight_smile: it didn’t return the last one.

I solved it this way:

get-adcomputer -filter * -SearchBase $strOU | where-object {$_.name -match “USLAXDT[0-9]{6}”} | sort name | select -ExpandProperty name -last 1

first I sort it, then get last 1.

This works.

Regards

Christian