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

Welcome Forums General PowerShell Q&A Getting the next largest number of the Workstation based on AD object?

This topic contains 3 replies, has 3 voices, and was last updated by

 
Participant
1 month, 2 weeks ago.

  • Author
    Posts
  • #119623

    Participant
    Points: 65
    Rank: Member

    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.

  • #119628

    Participant
    Points: 9
    Rank: Member
    $ADComputers = Get-ADComputer -Filter {Name -like "PRDVM*"}
    $Prefix = "PRDVM"
    $ComputerIndex = "$($($ADComputers.Count+1).ToString())"
    $NextComputerName = "$Prefix$($ComputerIndex.PadLeft(3,"0"))"
  • #119782

    Moderator
    Points: 174
    Team MemberHelping Hand
    Rank: Participant

    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.

    # 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
    }
    
  • #119823

    Participant
    Points: 65
    Rank: Member

    @neemo and @Wes,

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

     

You must be logged in to reply to this topic.