Getting the next largest number of the Workstation based on AD object?

Hi,

I need some assistance in the PowerShell scripting, so I can get the next available number of the Workstation based on Active Directory AD computer object.

My AD naming convention for computer objects like the below:

PRDVM001 PRDVM002 PRDVM003 ... PRDVM055
So how can I get the return from the Powershell script which basically says:

The next available AD computer name is PRDVM055
I just need to make sure that PRDVM055 is not already created in all of the AD domain before and is the largest number.

Thank you.

$ADComputers = Get-ADComputer -Filter {Name -like "PRDVM*"}
$Prefix = "PRDVM"
$ComputerIndex = "$($($ADComputers.Count+1).ToString())"
$NextComputerName = "$Prefix$($ComputerIndex.PadLeft(3,"0"))"

I like the succinct answer from Neemobeer. If your data is always clean, then you are good to go.
If there are gaps in the data and you want to fill them, this might help.
[pre]

Generate the test data

[System.Collections.ArrayList]$computerNames = 1…50 | ForEach-Object {“PRDVM{0:000}” -f $PSItem}

Case 1: All sequential, nothing missing.

Should be creating PRDVM051

[System.Collections.ArrayList]$array = $computerNames| ForEach-Object {[int]($PSItem -split ‘PRDVM’)[-1] }

Case 2: Missing one in the middle

Should create PRDVM019

Just uncomment the next line

$array.RemoveAt(18)

$array | foreach -Begin {$maximum = 1} -Process {
if ($maximum -lt $PSItem) {
$maximum = $PSItem
}
}

$missing = (Compare-Object -ReferenceObject $(1…$maximum) $array).InputObject
if ($missing) {
“PRDVM{0:000}” -f $missing
} else {
$maximum++
“PRDVM{0:000}” -f $maximum
}
[/pre]

@neemo and @Wes,

That is great, many thanks for the quick response and the suggestion :slight_smile: