Friday, September 8, 2017

How to preserve the naming convention

The problem

[string]$VMName = 'VM-EURO-UK-01'
[int]$NumberOfVMs = 12
$VMPrefix = ($VMName -split '(?=\d)',2)[0]
[int]$VMSuffix = ($VMName -split '(?=\d)',2)[1]

for($i=0;$i -lt $NumberOfVMs;$i++)
{
    $VMName = $VMPrefix+$VMSuffix

    Write-Host "VM Name is $VMName"

    $VMSuffix = $VMSuffix + 1
}
How to preserve the naming convention in Powershell?

The solution

[string]$VMName = 'VM-EURO-UK-01'
[int]$NumberOfVMs = 12

$VMPrefix = ($VMName -split '(?=\d)',2)[0]

[int]$VMSuffix = ($VMName -split '(?=\d)',2)[1] 

for($i=0;$i -lt $NumberOfVMs;$i++)
{
    $str = if($VMSuffix -le 9){
        "0{0}" -f $VMSuffix
    }
    else{
       $VMSuffix
    }  
    $VMName = $VMPrefix+$str

    Write-Host "VM Name is $VMName"

    $VMSuffix+=1
}

No comments:

Post a Comment