Is this “[int]($_.Name” not exactly what Olaf was saying, about not being able to define [int]‘nineteen’, except you’re trying to define [int]'PRD", [int]‘DR’, [int]‘TEST’.
$patterns = 'PROD', 'TEST', 'DR'
$CurrentADComputerName = $null
$NextADComputerName = $null
ForEach ( $prefix in $patterns) {
$CurrentADComputerName = Get-ADComputer -Filter "Name -like '$($prefix)*'" |
Sort-Object Name |
Select-Object -Expand Name |
Select-Object -Last 1
Write-Host "The current AD Computername for $prefix is: $CurrentADComputerName" -BackgroundColor Blue -ForegroundColor Yellow
$CurrentOULocation = (Get-ADComputer $CurrentADComputerName -Properties *).DistinguishedName
$NextADComputerName = Get-ADComputer -Filter "Name -like '$($prefix)*'" |
ForEach-Object {[int]($_.Name -replace '(?:.*?)(\d+)\Z', '$1')} |
Measure-Object -Maximum |
ForEach-Object {$prefix + (++$_.Maximum).ToString('000')}
Write-Host "The next available AD Computername for $prefix is: $NextADComputerName" -BackgroundColor Blue -ForegroundColor Green
Write-Host "Which can be deployed in OU: $CurrentOULocation `n`n" -BackgroundColor Blue -ForegroundColor White
}
OK, I have modified it like the above code, but so far I need to suppress the error with the AD object that is like the below:
Cannot convert value "PRD23-OLD" to type "System.Int32". Error: "Input string was not in a correct format."
Cannot convert value "TEST72-DEV" to type "System.Int32". Error: "Input string was not in a correct format."
and how to display the OU location like: domain.com/SITE 1/Server/Production not as DN with CN ?
No. You need to “extract/separate” the numbers from whatever string you have, cast it to [INT], treat it accordingly and use this for whatever further action you need to do.
I’d recommend for you to make a little step back and take your time to learn the basics of Powershell. You cannot learn a technology properly by guessing.