I am trying to automate the azure resource deployment using powershell.
Requirments : In a particular resource group(RG), there are multiple VMs. the naming convention are like,
XXX-XX-X-XXXXXX-VM-01,
XXX-XX-X-XXXXXX-VM-02,
XXX-XX-X-XXXXXX-VM-03.
I am trying to create a script which will look for the last sequence(is this case 03) and deploy the next VM with next sequence(here it should be 04).
I have the script to deploy the VM using powershell. Need help to fix the sequence logic.
2
Answers
I have a similar requirement and have been working on down the following route. In my case the numeric value is on the third element of the name, but I put in your value in hope this works for you.
With the returned value, I can then ceate the next VM.
Regards
As a general reusable solution:
usage:
Explanations:
param ([Parameter(ValueFromPipeline = $true)][String]$InputObject)
accepts (multiple) strings from the pipeline, each string is processed as$_
, the current itembegin
,process
andend
blocks, read about Functions Advanced Methods$Name, $Sequence = $_ -Split '(?=d*$)', 2
splits the current sting in the prefix ($name
) and the sequence number. See also: Regular Expressionif ([int]$Sequence -gt $Last) { $Last = $Sequence }
catch the highest number[int]
in front of the$Sequence
will force an numeric comparison$Name + (1 + $Last).ToString("D$($Last.Length)")
outputs the new string.(1 + $Last)
increase the$Last
number with 1. Note that the$Last
string will be automatically cast to an integer as the operant at the left hand side of the operator is an integer (1
).ToString("D$($Last.Length)")
will format the sequence to the same number of digits as contained by$Last
, see also: Pad a Number with Leading Zeros