Home > Net >  Powershell Query Active Directory and automatically generate an unused computer name
Powershell Query Active Directory and automatically generate an unused computer name

Time:09-03

I am trying to create a PowerShell script that will query active directory and automatically name a computer if the name doesn't already exist.

In my current environment, we rename laptops with generic names like ABClaptop1 after imaging until they are assigned to a specific user and get a different naming convention.

Ideally, the script would query active directory and see if name like ABClaptop1 - ABClaptop99 are available and randomly assign one of them. We usually have 20 or less laptops at a time with the generic naming convention.

Below is the script that I'm currently using that requires a lot of manual input and searching in AD for what is available:

$name = Read-Host 'Enter New Computer Name'
Rename-Computer -NewName $name
Add-Computer -ComputerName $name -DomainName domain -Credential domain\username -Restart -Force

CodePudding user response:

Get the current computer names from Active Directory, and then randomly select an unused one from 1-99:

$Prefix = "ABClaptop"
$Search = ("{0}*" -f $Prefix)
$ExistingComputers = Get-ADComputer -Filter { Name -like $Search }
$Name = 1..99 | Where-Object {
    "$Prefix$_" -notin $ExistingComputers.Name
} | Get-Random | ForEach-Object {
    "$Prefix$_"
}

If no names are available, $Name will be null, so be sure to check $Name is not null before continuing.

Continue onto your existing script:

Rename-Computer -NewName $Name
Add-Computer -ComputerName $Name -DomainName domain -Credential domain\username -Restart -Force
  • Related