Reputation: 25
I want to run a Powershell script withtin a SCCM task sequence, where a specific hostname by naming convention is entered, searched in Active Directory and checked for it's availability.
I found the following code on the internet:
$Prefix = $EnteredHostname -match '^(.*?)\d*$' | Out-Null # strip possibly trailing numbers
$Prefix = $Matches[1]
$Number = 0 # initialize last Number to zero
Get-ADComputer -Filter * |
Where-Object {$_.Name -match "^$Prefix(\d+)$" }|
Select-Object @{n='UsedNumber';e={[int]$Matches[1]}} | Sort-Object UsedNumber |
ForEach-Object {
While ($Number +1 -lt $_.UsedNumber){"{0}{1}" -f $Prefix,++$Number}
$Number = $_.UsedNumber
}
# if there was no gap get the next one.
"{0}{1}" -f $Prefix,++$Number
It is working fine but it only processes the last numbers after the entered Text. (Before that code is running, a Textbox appears where a desired hostname without numbers is entered and stored in the variable $enteredHostname).
Our companys naming convention is like this: "HostnameXXXX". For example: Hostname0005, Hostname0015, Hostname0150, ect. But this Code only delivers --> Hostname5, Hostname15, Hostname150, ..
How can I adjust the code to our naming convention, so that the hostnames are displayed correctly?
I couldn't figure it out myself yet. I'm new to Powershell, only have been using it for a few weeks
Any sggestions are highly appreaciated
Upvotes: 0
Views: 317
Reputation: 25001
The format operator (`-f') allows for padding of digits. In this case, the padding will provide extra zeroes in front of the number.
"{0}{1:d4}" -f $Prefix,++$Number
Upvotes: 1