Author Posts

October 30, 2015 at 8:14 am

Hi,

We're trying to create 10 virtual machines 1 through to 10 using the line below, how do I stop it adding the extra 0 on the final VM? I would like it look like VM-010101010 rather than VM-0101010010

PowerCLI C:\> 1..10 | % {New-VM -Name "VM-01010100$_" -VMHost x.x.x.x }

Name PowerState Num CPUs MemoryGB
—- ———- ——– ——–
VM-010101001 PoweredOff 1 0.250
VM-010101002 PoweredOff 1 0.250
VM-010101003 PoweredOff 1 0.250
VM-010101004 PoweredOff 1 0.250
VM-010101005 PoweredOff 1 0.250
VM-010101006 PoweredOff 1 0.250
VM-010101007 PoweredOff 1 0.250
VM-010101008 PoweredOff 1 0.250
VM-010101009 PoweredOff 1 0.250
VM-0101010010 PoweredOff 1 0.250

Many Thanks.

October 30, 2015 at 8:26 am

There may be a simpler approach, but you could try:

1..10 | % {New-VM -Name "VM-0101010$("{0:D2}" -f $_)" -VMHost x.x.x.x }

October 30, 2015 at 8:46 am

Tommy,

Here's one way:

1..10 | % { New-VM -Name $_.ToString("'VM-0101010'00") -VMHost x.x.x.x }

October 30, 2015 at 9:38 am

From the looks of it, you don't really want 1..10, you want 1001..1010

1001..1010 | % {New-VM -Name "VM-01010$_" -VMHost x.x.x.x }

October 31, 2015 at 6:10 am

Let me expand on Curtis's and Chris's point, You need to identify what portion of the name are you going to increment. If the static portion is "VM-010101" and the dynamic portion is the last three digits, then think of the name as "VM-010101XXX" with XXX as the variable that you will increment.

001..010|%{"VM-010101$_"}
VM-0101011
VM-0101012
VM-0101013
VM-0101014
VM-0101015
VM-0101016
VM-0101017
VM-0101018
VM-0101019
VM-01010110

This approach works but does not give you the format you are looking for.

 
001..010|%{"VM-010101$("{0:D3}" -f $_)"}
VM-010101001
VM-010101002
VM-010101003
VM-010101004
VM-010101005
VM-010101006
VM-010101007
VM-010101008
VM-010101009
VM-010101010

This works as well but be aware I left the number being incremented as three digits to match the variable portion of the example, "XXX". However when using integers the leading zeros are dropped and

  1..10|%{"VM-010101$("{0:D3}" -f $_)"} 

works the same way.
The other approach is if the dynamic portion of the name is 4 digits, i.e. "VM-01010XXXX" in this case the leading zeros are not an issue because your base number is 1001. If you needed to account for the zeros as in XXXX = 0001 then you would adjust the formating

 1..10|%{"VM-01010$("{0:D4}" -f $_)"} 

October 31, 2015 at 11:42 pm

Many thanks for all your replies, it's much appreciated!