简体   繁体   中英

Powershell Query Active Directory and automatically generate an unused computer name

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

Thanks in advance for any suggestions.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM