Hi Folks,
Hope you’re all well!
We have a number of virtual machines. Let’s say:
ThickGit_PC1
ThickGit_PC2
ThickGit_PC3
ThickGit_PC4
ThickGit_PC5
A team of us are building them manually. However, I want to be able to script the creation of the new machine by typing (Get-VM ThickGit_PC* | Select Name | Sort Name | Select –Last 1), which will give me the name of the last machine, but how do I increment that by one so I can feed that to the –Name parameter of the New-VM cmdlet?
I know I can use the –ExpandProperty parameter within the ‘Select’ cmdlet to make it a string, but I just don’t know how to automatically go from there to get it to create ‘ThickGit_PC6’.
Any ideas?!
Cheers.
TG
Here is an example:
# repalace this with your method to get the last name, don't forget to use -ExpandProperty
$Lastname = 'ThickGit_PC5'
# Check if name ends with one or more digits
if($LastName -match '\d+$')
{
# Extract the digits in the end of the name and add 1
$NextNumber = [int]$Matches[0] + 1
}
else
{
# Name did not end with number, use number 1
$NextNumber = 1
}
# Create a new name
$NewName = "ThickGit_PC$NextNumber"
I think something like this would work:
1..10 | foreach{
$vmName = "ThickGit_PC{0}" -f $_
$vm = Get-VM -ComputerName $vmName
if ($vm) {
"{0} exists" -f $vmName
}
else {
New-VM -Name $vmName
}
}
As a side note, you are going to run into issues sorting names if that is your naming convention. If you create some mock names:
PS C:\Windows\System32\WindowsPowerShell\v1.0> $vm = 1..10 | foreach{New-Object -TypeName PSObject -Property @{Name = ("ThickGit_PC{0}" -f $_)}}
PS C:\Windows\System32\WindowsPowerShell\v1.0> $vm
Name
----
ThickGit_PC1
ThickGit_PC2
ThickGit_PC3
ThickGit_PC4
ThickGit_PC5
ThickGit_PC6
ThickGit_PC7
ThickGit_PC8
ThickGit_PC9
ThickGit_PC10
When you sort these, look what happens:
PS C:\Windows\System32\WindowsPowerShell\v1.0> $vm | Sort-Object Name -Descending
Name
----
ThickGit_PC9
ThickGit_PC8
ThickGit_PC7
ThickGit_PC6
ThickGit_PC5
ThickGit_PC4
ThickGit_PC3
ThickGit_PC2
ThickGit_PC10
ThickGit_PC1
We sorted descending and expect 10 to be at the top, but the sort is just seeing it as 1 and zero, not 10. You should consider pre-pending your names with zeros. If your company is going to have 9999 machines max, you would prepend with 3 zeros lke so:
PS C:\Windows\System32\WindowsPowerShell\v1.0> $vm = 1..10 | foreach{$num = $_.ToString("0000");New-Object -TypeName PSObject -Property @{Name = ("ThickGit_PC{0}" -f $num)}}
PS C:\Windows\System32\WindowsPowerShell\v1.0> $vm
Name
----
ThickGit_PC0001
ThickGit_PC0002
ThickGit_PC0003
ThickGit_PC0004
ThickGit_PC0005
ThickGit_PC0006
ThickGit_PC0007
ThickGit_PC0008
ThickGit_PC0009
ThickGit_PC0010
Now when we sort, it performs as expected.
PS C:\Windows\System32\WindowsPowerShell\v1.0> $vm | Sort-Object Name -Descending
Name
----
ThickGit_PC0010
ThickGit_PC0009
ThickGit_PC0008
ThickGit_PC0007
ThickGit_PC0006
ThickGit_PC0005
ThickGit_PC0004
ThickGit_PC0003
ThickGit_PC0002
ThickGit_PC0001