I'm trying to append a specific suffix to a list of VMs using PowerCLI, the problem is that I'm not able to match the start of the string and replace only that, instead what I'm getting is appending my prefix to every letter of the name.
Here's the code:
$vApp="some-vapp"
$prefix = "SA-"
$VMlist = Get-VApp -Name $vApp | Get-VM
for ($i=0; $i -lt $VMlist.length; $i++) {
$destVMName = $VMlist[$i].Name -replace $^.Name, $prefix
$VMlist[$i] | set-vm -Name $destVMName -Confirm:$false -RunAsync:$true
}
The problem is in the regex
$VMlist[$i].Name -replace $^.Name, $prefix
Here's an example of the output:
PS > $VMlist[0].Name
Shared_AD_W2012
PS > $VMlist[0].Name -replace $^.Name, $prefix
SA-SSA-hSA-aSA-rSA-eSA-dSA-_SA-ASA-DSA-_SA-WSA-2SA-0SA-1SA-2SA-
Desired result would be: SA-Shared_AD_W2012
Use an expandable string:
$prefixedString = "$prefix$($VMlist[0].Name)"
or regular string concatenation:
$prefixedString = $prefix + $VMlist[0].Name