VMware Cloud Community
jasonrobinson
Enthusiast
Enthusiast

Building VMs via CSV

Hey guys,

Trying to write a script that pulls info from a csv and builds the vm shells. For the most part I have been trying to keep it really simple and then add some error handling around it later. Right now I have ran into a snag. So of my vms will have one hard disks and others will have two. I can create the vm's with two hard disks fine, the problem I run into is when I only want to create the one hard disk. The script is looking for a value in the CSV under DiskMB2. So I need to change this script to look at the DiskMB2 column in the CSV field and if the value is blank or null skip it and move on. Below is the script I am currently using, thanks for any and all help.

foreach ($f in (Import-Csv d:\vmparm.csv)) {New-VM -name $f.vmname -VMHost $f.hostname -DiskMB $f.diskmb1,$f.diskMB2 -MemoryMB $f.memorymbv+-NumCpu $f.numcpu -GuestId $f.guestid -NetworkName $f.netname+}

Jason @jrob24
0 Kudos
3 Replies
jasonrobinson
Enthusiast
Enthusiast

Nevermind I figured it out. Below is the code for anyone if they are interested

foreach ($f in (Import-Csv d:\vmparm.csv)){

if ($f.diskMB2 > NULL)

{New-VM -name $f.vmname -VMHost $f.hostname -DiskMB $f.diskmb1,$f.diskMB2 -MemoryMB $f.memorymb` *

+

-NumCpu $f.numcpu -GuestId $f.guestid -NetworkName $f.netname}

+

else

{New-VM* -name $f.vmname -VMHost $f.hostname -DiskMB $f.diskmb1 -MemoryMB $f.memorymb`<

+

-NumCpu $f.numcpu -GuestId $f.guestid -NetworkName $f.netname}

+

}

*

Jason @jrob24
0 Kudos
admin
Immortal
Immortal

Hello,

how can I define in your solution the datstore as well. Maybe it is also possible to place these VMs in a specific Resource Pool.

Many thanks in advance.

best regards

0 Kudos
RvdNieuwendijk
Leadership
Leadership

To define the datastore and the resourcepool as well, you could do something like this:

Import-Csv -Path d:\vmparm.csv | ForEach-Object {
  $VM = New-VM -name $_.vmname -VMHost $_.hostname -DiskMB $_.diskmb1 -MemoryMB $_.memorymb `
	       -NumCpu $_.numcpu -GuestId $_.guestid -NetworkName $_.netname -Datastore $_.datastore -ResourcePool $_.resourcepool 
  if ($_.diskMB2) {
    New-HardDisk -VM $VM -CapacityKB (1024*$_.diskMB2)
  }
}

Regards, Robert

Message was edited by: RvdNieuwendijk

Blog: https://rvdnieuwendijk.com/ | Twitter: @rvdnieuwendijk | Author of: https://www.packtpub.com/virtualization-and-cloud/learning-powercli-second-edition
0 Kudos