drak
drak

Reputation: 87

Append a prefix to a string in PowerShell/PowerCLI

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

Upvotes: 2

Views: 1629

Answers (2)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174465

Use an expandable string:

$prefixedString = "$prefix$($VMlist[0].Name)"

or regular string concatenation:

$prefixedString = $prefix + $VMlist[0].Name

Upvotes: 1

Martin Brandl
Martin Brandl

Reputation: 58931

You don't have to use a regex here, just use a format string:

"{0}{1}" -f $prefix, $VMlist[0].Name

Upvotes: 1

Related Questions