I would like to get missing computer hostnames in our Active Directory.
Currently we have a naming convention for notebooks:
NB-DE-00001
and for PC's:
PC-DE-00001
Currently, however, some hostnames have not been incremented, but a higher number has simply been chosen manually.
In AD, for example
NB-DN-00001
NB-DE-00004
Now I would like to determine the missing ones so 2-3 in this example.
Is there a PowerShell way to do this?
There are going to be a number of ways to do this. But this is a decent starting point to list all of the missing numbers in five-digit format.
$Computers = Get-ADComputer -Filter "Name -like '*-*'" -SearchBase 'OU Path' |
Where Name -match '-\d+$' | Select-Object -Expand Name
[int[]]$UsedNumbers = $Computers -replace '.*?-(?=\d+$)' | Sort-Object { [int]$_ }
1..$UsedNumbers[-1] | Where {$_ -notin $UsedNumbers} |
Foreach-Object { "{0:d5}" -f $_ }
You have not specified if NB-DE-*
, NB-DN-*
, or PC-DE-*
use the same pool of numbers, if those systems share the same OUs, or if PC-DE-00001
can coexist with NB-DN-00001
.
I just found a really dirty workaround but it works.. For me as a beginner it's okay but I would like to improve my skills so I would appreciate it when you guys could give me some tips.
My solution right now:
My first step is to get a sorted list of computers and notebooks (I just need theese filters for stuff)
$ADnbSorted = Get-ADComputer -SearchBase 'OU=computers,dc=example,dc=com' -Filter {(Name -like "NB-DE-*") -and (Name -notlike "NB-DE-M*") }| Sort-Object | Select-Object Name
$ADpcSorted = Get-ADComputer -SearchBase 'OU=computers,dc=example,dc=com' -Filter {(Name -notlike "PC-DE-R*") -and (Name -like "PC-DE-*") } | Sort-Object | Select-Object Name
My next step is that I create a template list how a correct list of hostnames should look like
$templatehostname = 1..$ADpcSorted[-1].Name |
ForEach-Object{ "$prefix" + $_.ToString("00000")}
I use prefix because its an little application where the user can enter if he wants to know all PC's Unkown and all Notebook Unkown Hostnames :)
After that I just compare both of theese and add the missing entrys just to a new list
> ForEach($Hostname in $templatehostname)
> {
> if (-Not ($ADpcSorted.Name.Contains($Hostname)))
> {
> $freeHostname += $Hostname
> }
> }
I'm sorry for that bunch of shit :)
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.