Given a list of strings such as: apple01
, apple02
, and apple04
, banana02
, cherry01
, how would you come up with the first available serial number of each type -- that is, apple03
if I ask about apple
, or banana01
if I ask about banana
, and cherry02
if I ask about cherry
?
I'm tasked with automating the creation of Azure VM's, and these strings are actually host names of existing VM's, as reported by the Azure Powershell command (Get-AzureRmResourceGroupDeployment -ResourceGroupName "$azureResGrpName2").DeploymentName
(or anything effectively similar).
Update: Here's my working code:
$rgdNames = (Get-AzureRmResourceGroupDeployment -ResourceGroupName "$azureResGrpName").DeploymentName
$siblings = $rgdNames | Where-Object{$_ -match "^($hostname)(\d+)$" }
if ($siblings) {
# Make a list of all numbers in the list of hostnames
$serials = @()
foreach ($sibling in $siblings) {
# $sibling -split ($sibling -split '\d+$') < split all digits from end, then strip off everything at the front
# Then convert it to a number and add that to $serials
$hostnumber = [convert]::ToInt32([string]$($sibling -split ($sibling -split '\d+$'))[1], 10)
$serials += $hostnumber
}
foreach ($i in 1..$siblingsMax){ # Iterate over all valid serial numbers
if (!$serials.Contains($i)) { # Stop when we find a serial number that isn't in the list of existing hosts
$serial = $i
break
}
}
} else {
$serial = 1
}