PowerCLI

 View Only
Expand all | Collapse all

Create VM using PowerCLI and csv file

Sivaramsharmar

SivaramsharmarJan 06, 2015 11:26 AM

esxi1979

esxi1979Dec 13, 2015 06:02 AM

  • 1.  Create VM using PowerCLI and csv file

    Posted Feb 22, 2013 03:02 PM

    I know that there is a lot of info out there about this and I think I have a prety good working script.  A lot was borrowed from this thread, http://communities.vmware.com/thread/315193 many thanks to LucD.

    My code is as follows:

    ## Deploy VMs from CSV File
    ## Much borrowed from http://communities.vmware.com/thread/315193?start=15&tstart=0


    ## Imports CSV file
    Import-Csv "C:\guests.csv" -UseCulture | %{
    ## Gets Customization info to set NIC to Static and assign static IP address
        Get-OSCustomizationSpec $_.Customization | Get-OSCustomizationNicMapping | `
        Set-OSCustomizationNicMapping -IpMode UseStaticIP -IpAddress $_."IP Address" `
            -SubnetMask $_.Subnet -DefaultGateway $_.Gateway -Dns $_.DNS
        $vm=New-VM -Name $_."Server Name" -Template $_.Template -Host $_."Esx Host" `
            -Datastore $_.Datastore -OSCustomizationSpec $_.Customization `
            -Confirm:$false -RunAsync
    ## .......
    }

    It will go through and clone the VM, and then it looks like it is running the OSCustomizaitonSpec and then it bombs.  It does clean up the bad VM.  The Recent Tasks shows "clone virtual machine fails a specified parapeter was not correct. hostname"

    The issue is that I am not trying to set a hostname with the OSCustomixationSpec, I am only trying to put in IP address info.

    I am runningn PowerCLI 5.0.1 build 581491

    My ESXi host is 5.0.0 build 914586

    My vCenter Server is Ver 5.0.0 build 623373

    I opened a new thread, becuase the age of the old thread.  Not sure if that is the best way to do things.     



  • 2.  RE: Create VM using PowerCLI and csv file

    Posted Feb 22, 2013 03:07 PM

    Could it be that the "Esx Host" column in the CSV doesn't contain a correct ESXi hostname ?

    I suspect the error might be about the VMhost or Host parameter on the New-VM cmdlet.

    Could you perhaps include the complete error message you get in PowerCLI ?



  • 3.  RE: Create VM using PowerCLI and csv file

    Posted Feb 22, 2013 03:19 PM

    Hi LucD,

    I do not get the error in power CLI.  Here is the output I get.

    PowerCLI C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\custom> .
    \Deploy.PS1

                  SpecId Position IPMode           IPAddress       DefaultGateway
                  ------ -------- ------           ---------       --------------
    ...rk 10.10.160.0/21        1 UseStaticIP      10.10.163.10    10.10.160.1

    No issues there.  I get the error in Recent Tasks on the ESXi host.  I am not sure if I have to go into the vpxd.log to find more info or not.  I am getting a bundle of the logs on the target host.

    If there is a specific log file location that I should be looking at please advise:-)

    I verified that the ESX Host is a valid host in the cluster I am hopeing to work on.

    Your help is greatly apreciated.



  • 4.  RE: Create VM using PowerCLI and csv file

    Posted Feb 22, 2013 03:35 PM

    It gets to the Reconfiguring VM and that is when it fails.  IT is at 95% of the clone option.

    Reconfigured mciptiershw013.********.lan
    info
    2/22/2013 10:31:31 AM
    mciptiershw013.*********.lan
    ASP\j********m

    Not much more info there.



  • 5.  RE: Create VM using PowerCLI and csv file

    Posted Feb 22, 2013 03:40 PM

    I see, let's dig a bit deeper.

    Is that template for a Linux OS ?

    Try this alternative where we do the customization after the clone (New-VM) cmdlet.

    ## Imports CSV file
    Import-Csv "C:\guests.csv" -UseCulture | %{
    ## Gets Customization info to set NIC to Static and assign static IP address
        Get-OSCustomizationSpec $_.Customization | Get-OSCustomizationNicMapping | `
       
    Set-OSCustomizationNicMapping -IpMode UseStaticIP -IpAddress $_."IP Address" `
            -SubnetMask $_.Subnet -DefaultGateway $_.Gateway -Dns $_.DNS
       
    $vm=New-VM -Name $_."Server Name" -Template $_.Template -Host $_."Esx Host" `
            -Datastore $_.Datastore -Confirm:$false -RunAsync |
            Set-OSCustomizationSpec -OSCustomizationSpec $_.Customization
    ## .......
    }

    And I would also be interested to see the content of the OSCustomizationSpec (make sure to hide the sensitive data).

    Can you do a

    Get-OSCustomizationSpec $_.Customization | Select * 

    You can replace the $_.Customization with the actual name, as it is defined in the CSV, for that oscustomizationspec.

    If the error keeps popping up, a closer look at the vpxd logs would be the next course of action.



  • 6.  RE: Create VM using PowerCLI and csv file

    Posted Feb 22, 2013 03:57 PM

    Here is the output from PowerCLI C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\custom> G
    et-OSCustomizationSpec "MCI - Windows 2008 R2 Standard - ************ Trusted N
    etwork 10.10.192.0/21" | Select *

    As you can see it is a windows Guest OS

    Name                  : MCI - Windows 2008 R2 Standard - ********Trusted
                            Network 10.10.192.0/21
    Type                  : Persistent
    ServerId              : /VIServer=@mcipvcntw001.***.****.lan:443/
    Server                : MCIPVCNTW001.***.****.lan
    LastUpdate            : 7/5/2012 4:54:39 PM
    DomainAdminUsername   : ******
    DomainUsername        : ******
    Description           :
    AutoLogonCount        : 1
    ChangeSid             : True
    DeleteAccounts        : False
    DnsServer             :
    DnsSuffix             :
    Domain                : **************
    FullName              : ***** Infrastructure
    GuiRunOnce            :
    NamingPrefix          :
    NamingScheme          :
    OrgName               : ******************
    OSType                : Windows
    ProductKey            : 82VMD-*****-*****-******-H2X8F
    TimeZone              : Central (U.S. and Canada)
    Workgroup             :
    LicenseMode           : PerSeat
    LicenseMaxConnections :
    EncryptionKey         :
    ExtensionData         : VMware.Vim.CustomizationSpecItem
    Id                    : MCI - Windows 2008 R2 Standard - ***********Trusted
                            Network 10.10.192.0/21
    Uid                   : /VIServer=@mcipvcntw001.***.****.lan:443/OSCustomizatio
                            nSpec=MCI - Windows 2008 R2 Standard - **********Tr
                            usted Network 10.10.192.0&slash;21/



  • 7.  RE: Create VM using PowerCLI and csv file

    Posted Feb 22, 2013 04:18 PM

    OK when I run the updated script, 1st I was warned that I had to run it in a 32bit PowerCLI shell.

    PowerCLI C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\custom> .
    \Deploy1.PS1

                  SpecId Position IPMode           IPAddress       DefaultGateway
                  ------ -------- ------           ---------       --------------
    ...rk 10.10.160.0/21        1 UseStaticIP      10.10.163.10    10.10.160.1
    Set-OSCustomizationSpec : This cmdlet requires 32bit process. Please run PowerC
    LI in 32 bit mode.
    At C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\custom\Deploy1
    .ps1:12 char:26
    +         Set-OSCustomizationSpec <<<<  -OSCustomizationSpec $_.Customization
        + CategoryInfo          : NotSpecified: (:) [Set-OSCustomizationSpec], ViE
       rror
        + FullyQualifiedErrorId : VMware.VimAutomation.Sdk.Types.V1.ErrorHandling.
       VimException.ViError,VMware.VimAutomation.ViCore.Cmdlets.Commands.SetCusto
      mizationSpec

    Once I did this, I got a differnt error.

    PowerCLI C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\custom> .
    \Deploy1.ps1

                  SpecId Position IPMode           IPAddress       DefaultGateway
                  ------ -------- ------           ---------       --------------
    ...rk 10.10.160.0/21        1 UseStaticIP      10.10.163.10    10.10.160.1
    Set-OSCustomizationSpec : The input object cannot be bound to any parameters fo
    r the command either because the command does not take pipeline input or the in
    put and its properties do not match any of the parameters that take pipeline in
    put.
    At C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\custom\Deploy1
    .ps1:12 char:26
    +         Set-OSCustomizationSpec <<<<  -OSCustomizationSpec $_.Customization
        + CategoryInfo          : InvalidArgument: (CloneVM_Task:PSObject) [Set-OS
       CustomizationSpec], ParameterBindingException
        + FullyQualifiedErrorId : InputObjectNotBound,VMware.VimAutomation.ViCore.
       Cmdlets.Commands.SetCustomizationSpec

    This error outputed, prior to the VM being cloned in the Recent Tasks.  Is this because the -RunAsync is set?

    Either way once the VM started cloning, it died at the same point as the prior one did.

    I have manually run the clone and it does work when you are manually inputting the value.



  • 8.  RE: Create VM using PowerCLI and csv file

    Posted Feb 22, 2013 04:58 PM

    I think that I got it!  Well most of it

    So in the OSCustomizationSpec that I was using, under the Computer Name Section, the NetBIOS Name was set to the radio button for Enter a name in the DeployWizard.

    So the name it was looking for was the Host Name of the VM!

    The one issue I now see is that on the Virtual Mahcine Tab from the host, where it lists all of the VMs Names, State, Status, Host Mem, Guest Mem, VMware Tools, DNS Name,....

    The DNS Name is incorrect.  the VM - Name is mvicptiershw013.*************.lan however the DNS name is mciptiershw013w.  Is there a way to set this?



  • 9.  RE: Create VM using PowerCLI and csv file

    Posted Feb 22, 2013 05:16 PM

    The fact that you had a prompt in the OSCustomizationSpec explains the error.

    There are several ways to change the hostname inside the guest OS.

    You can use the WMI cmdlet, but that requires the VM to be accessible over the network.

    Or use the Invoke-VMScript and execute the WMI cmdlet or the netdom command inside the guest OS.

    But once you correct the NetBIOS name in the OSCustomizationSpec, is the generated hostname still incorrect ?



  • 10.  RE: Create VM using PowerCLI and csv file

    Posted Feb 22, 2013 05:53 PM

    No it looks like if I correc the NetBIOS name I am ok.

    Can I use the  Set-OSCustomizationSpec -Name filed and then pass it a name from the csv file?

    If so please let me know where I would be placing this info.  I was thinking after the Get-OSCustomizationSpec line.

    Please advise, and again thanks for all your help.

    Tony



  • 11.  RE: Create VM using PowerCLI and csv file

    Posted Feb 22, 2013 06:48 PM

    No, the Name parameter on the Set-OSCustomizationSpec cmdlet is for the name you want to give to the customizationspec.

    You will have to use the NamingScheme and NamingPrefix parameters.

    For example, this

    $cust = Get-OSCustomizationSpec -Name Test 
    Set-OSCustomizationSpec
    -OSCustomizationSpec $cust -NamingScheme Fixed -NamingPrefix MyName

    will change the Customizationspec as follows



  • 12.  RE: Create VM using PowerCLI and csv file

    Posted Feb 22, 2013 08:36 PM

    LucD,

    That seems to have done it.  I do have one final question.  Is there a way to limit the amount of VMs that it attemps to create at a time, other than limiting the number that are in the CSV file?  I am concernted that we may beat the crunck out of the hosts and affect the currenlty running VMs

    Here is the script so far.

    ## Deploy VMs from CSV File
    ## Much borrowed from http://communities.vmware.com/thread/315193?start=15&tstart=0


    ## Imports CSV file
    Import-Csv "C:\temp\TestDeploy1" -UseCulture | %{
    ## Gets Customization info to set NIC to Static and assign static IP address
        Get-OSCustomizationSpec $_.Customization | Get-OSCustomizationNicMapping | `
    ## Sets the Static IP info
        Set-OSCustomizationNicMapping -IpMode UseStaticIP -IpAddress $_."IP Address" `
            -SubnetMask $_.Subnet -DefaultGateway $_.Gateway -Dns $_.DNS
    ## Sets the name of the VMs OS
        $cust = Get-OSCustomizationSpec -Name Test
        Set-OSCustomizationSpec -OSCustomizationSpec $cust -NamingScheme Fixed -NamingPrefix $_.VMName
    ## Creates the New VM from the template
        $vm=New-VM -Name $_."Server Name" -Template $_.Template -Host $_."Esx Host" `
            -Datastore $_.Datastore -OSCustomizationSpec $_.Customization `
            -Confirm:$false -RunAsync
    ## .......
    }



  • 13.  RE: Create VM using PowerCLI and csv file

    Posted Feb 22, 2013 10:59 PM

    In which sense do you want to limit this ?

    The number of parallel clone jobs that can run at a given time ?

    Or a maximum number of cloned VMs that can be created (irrespective of what number of lines are in the CSV file).



  • 14.  RE: Create VM using PowerCLI and csv file

    Posted Feb 25, 2013 01:24 PM

    Ideally I would like to limit the number of paralle clone jobs.  Just to allow that warm fuzzy feeling, to not over strees an environment.  I know that it should not be an issue but by being able to limit the number of clones there is more of a feeling of control over how much load you are going to drop onto a system.



  • 15.  RE: Create VM using PowerCLI and csv file
    Best Answer

    Posted Feb 25, 2013 01:34 PM

    A very simple and straightforward brake system :-)

    ## Deploy VMs from CSV File
    ## Much borrowed from http://communities.vmware.com/thread/315193?start=15&tstart=0  
    
    $maxJobs = 3 
    $currentJobs
    = 0
    ## Imports CSV file
    Import-Csv "C:\temp\TestDeploy1" -UseCulture | %{ ## Gets Customization info to set NIC to Static and assign static IP address     Get-OSCustomizationSpec $_.Customization | Get-OSCustomizationNicMapping | `
    ## Sets the Static IP info
        Set-OSCustomizationNicMapping -IpMode UseStaticIP -IpAddress $_."IP Address" `
            -SubnetMask $_.Subnet -DefaultGateway $_.Gateway -Dns $_.DNS
    ## Sets the name of the VMs OS
        $cust = Get-OSCustomizationSpec -Name Test
        Set-OSCustomizationSpec -OSCustomizationSpec $cust -NamingScheme Fixed -NamingPrefix $_.VMName
    ## Creates the New VM from the template
        $vm=New-VM -Name $_."Server Name" -Template $_.Template -Host $_."Esx Host" `
            -Datastore $_.Datastore -OSCustomizationSpec $_.Customization `
           
    -Confirm:$false -RunAsync

       
    $currentJobs = Get-Job -State Running | Measure-Object | Select -ExpandProperty Count
       
    while($currentJobs -ge $maxJobs){       sleep 30
         
    $currentJobs = Get-Job -State Running | Measure-Object | Select -ExpandProperty Count
        }
    ## ....... }

    You can be more selective on getting the current jobs. You could for example check if the name of the jobs shows that they are actually cloning jobs.



  • 16.  RE: Create VM using PowerCLI and csv file

    Posted Mar 07, 2013 11:55 AM

    Hi,

    need help to install the 100 linux vm's with the powerCLI,

    I read the previce scripts and used the same, i able to create the vm's but all the vm's are comming with the same host name( but the vm display name is redding from the excel as in csv file ) and the ip also now getting assined.

    .ps1 file :

    ---------------------------------------------------------------------------------------------------------------------------------------------

    Import-Csv "C:\guests.csv" -UseCulture | %{
        Get-OSCustomizationSpec $_.Customization | Get-OSCustomizationNicMapping | `
        Set-OSCustomizationNicMapping -IpMode UseStaticIP -IpAddress $_."IP Address" `
            -SubnetMask $_.Subnet -DefaultGateway $_.Gateway -Dns $_.DNS
        $vm=New-VM -Name $_."Server Name" -Template $_.Template -Host $_."Esx Host" `
            -Datastore $_.Datastore -Confirm:$false -RunAsync |
            Set-OSCustomizationSpec -OSCustomizationSpec $_.Customization

    --------------------------------------------------------------------------------------------------------------------------------------------

    .csv hedding :

    --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    Server   NameEsx HostDatastoreTemplateCustomizationIP AddressSubnetGatewayDNS

    --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    Error message :

    ------------------------------------------------------------------------------------------------------------------------------------------

    Set-OSCustomizationNicMapping : 3/7/2013 4:19:11 PM    Set-OSCustomizationNicMa
    pping        You must not provide Wins or Dns when you create NIC mapping for a
    customization spec with type 'linux'.
    At C:\vmps2.ps1:3 char:34
    +     Set-OSCustomizationNicMapping <<<<  -IpMode UseStaticIP -IpAddress $_."IP
    Address" `
        + CategoryInfo          : InvalidArgument: (:) [Set-OSCustomizationNicMapp
       ing], ViError
        + FullyQualifiedErrorId : Core_NicMappingCmdletBase_ValidateParameters_Lin
       uxAndWins,VMware.VimAutomation.ViCore.Cmdlets.Commands.SetOSCustomizationN
      icMapping

    Set-OSCustomizationSpec : The input object cannot be bound to any parameters fo
    r the command either because the command does not take pipeline input or the in
    put and its properties do not match any of the parameters that take pipeline in
    put.
    At C:\vmps2.ps1:7 char:32
    +         Set-OSCustomizationSpec <<<<  -OSCustomizationSpec $_.Customization
        + CategoryInfo          : InvalidArgument: (CloneVM_Task:PSObject) [Set-OS
       CustomizationSpec], ParameterBindingException
        + FullyQualifiedErrorId : InputObjectNotBound,VMware.VimAutomation.ViCore.
       Cmdlets.Commands.SetCustomizationSpec

    Set-OSCustomizationNicMapping : 3/7/2013 4:19:16 PM    Set-OSCustomizationNicMa
    pping        You must not provide Wins or Dns when you create NIC mapping for a
    customization spec with type 'linux'.
    At C:\vmps2.ps1:3 char:34
    +     Set-OSCustomizationNicMapping <<<<  -IpMode UseStaticIP -IpAddress $_."IP
    Address" `
        + CategoryInfo          : InvalidArgument: (:) [Set-OSCustomizationNicMapp
       ing], ViError
        + FullyQualifiedErrorId : Core_NicMappingCmdletBase_ValidateParameters_Lin
       uxAndWins,VMware.VimAutomation.ViCore.Cmdlets.Commands.SetOSCustomizationN
      icMapping

    Set-OSCustomizationSpec : The input object cannot be bound to any parameters fo
    r the command either because the command does not take pipeline input or the in
    put and its properties do not match any of the parameters that take pipeline in
    put.
    At C:\vmps2.ps1:7 char:32
    +         Set-OSCustomizationSpec <<<<  -OSCustomizationSpec $_.Customization
        + CategoryInfo          : InvalidArgument: (CloneVM_Task:PSObject) [Set-OS
       CustomizationSpec], ParameterBindingException
        + FullyQualifiedErrorId : InputObjectNotBound,VMware.VimAutomation.ViCore.
       Cmdlets.Commands.SetCustomizationSpec

    Set-OSCustomizationNicMapping : 3/7/2013 4:19:22 PM    Set-OSCustomizationNicMa
    pping        You must not provide Wins or Dns when you create NIC mapping for a
    customization spec with type 'linux'.
    At C:\vmps2.ps1:3 char:34
    +     Set-OSCustomizationNicMapping <<<<  -IpMode UseStaticIP -IpAddress $_."IP
    Address" `
        + CategoryInfo          : InvalidArgument: (:) [Set-OSCustomizationNicMapp
       ing], ViError
        + FullyQualifiedErrorId : Core_NicMappingCmdletBase_ValidateParameters_Lin
       uxAndWins,VMware.VimAutomation.ViCore.Cmdlets.Commands.SetOSCustomizationN
      icMapping

    Set-OSCustomizationSpec : The input object cannot be bound to any parameters fo
    r the command either because the command does not take pipeline input or the in
    put and its properties do not match any of the parameters that take pipeline in
    put.
    At C:\vmps2.ps1:7 char:32
    +         Set-OSCustomizationSpec <<<<  -OSCustomizationSpec $_.Customization
        + CategoryInfo          : InvalidArgument: (CloneVM_Task:PSObject) [Set-OS
       CustomizationSpec], ParameterBindingException
        + FullyQualifiedErrorId : InputObjectNotBound,VMware.VimAutomation.ViCore.
       Cmdlets.Commands.SetCustomizationSpec

    -----------------------------------------------------------------------------------------------------------------------------------------------------------------

    Regrds,

    Mohan.



  • 17.  RE: Create VM using PowerCLI and csv file

    Posted Mar 07, 2013 07:32 PM

    For a Linux OS you can not specify the DNS parameter on the Set-OSCustomization cmdlet.

    First try leaving out the this DNS parameter



  • 18.  RE: Create VM using PowerCLI and csv file

    Posted Mar 08, 2013 09:51 AM

    Thanks LucD its working, i can able to install,

    is thare any option to run a script or command's after installation the linux vm's onely after the first start.

    Regards,

    Mohan.



  • 19.  RE: Create VM using PowerCLI and csv file

    Posted Oct 06, 2014 09:21 PM

    Trying to make this work,  and it is failing, I THINK because I have no OSCustomizationSpec defined.  This would be a prereq to make this work, and not sure how to set it up.  Will figure it out, but might want to add something so this works out of the box.
      And thanks for the script!



  • 20.  RE: Create VM using PowerCLI and csv file

    Posted Jan 05, 2015 01:34 PM

    Hi Lucd,

    I am not able to limit the VM Cloning as per your below script. Please suggest.

    $MaxClones = 3

    $CurrentClones = 0

    $CSV = "C:\users\$env:username\Linux.csv"

    $nvm = Import-CSV $CSV -Useculture

    $nvm | %{

    New-VM -Name $_.Name -vm $(Get-Cluster $_.cluster | Get-ResourcePool $_.SVMLocation | get-vm $_.SourceVM) -VMHost $(Get-Cluster $_.cluster | Get-VMHost -state "connected" | Get-Random) -ResourcePool $(Get-Cluster $_.cluster | Get-ResourcePool $_.rp) -datastore $(Get-Cluster $_.cluster | Get-DataStore $_.ds) -Notes $_.Notes -RunAsync

    $CurrentClones = Get-Job -State Running | Measure-Object | Select -ExpandProperty Count

      while($CurrentClones -ge $MaxClones)

      {

      sleep 30

      $CurrentClones = Get-Job -State Running | Measure-Object | Select -ExpandProperty Count

      }

    }



  • 21.  RE: Create VM using PowerCLI and csv file

    Posted Jan 05, 2015 03:32 PM

    What happens, do all clone jobs get started ?

    Did you check the value you have in $CurrentClones ?

    You could display the value of this variable on screen from within the While-loop, that way you should be able to follow what is going on.



  • 22.  RE: Create VM using PowerCLI and csv file

    Posted Jan 05, 2015 04:55 PM

    Hi Lucd,

    I have passed 5 VM's in CSV sheet and after execution of this script 5 VM's started to clone at a time.

    I have cross checked and $CurrentClones is having 0 value.

    I will try to pass $currentclones in while loop and get back to you.

    Thanks Lucd.



  • 23.  RE: Create VM using PowerCLI and csv file

    Posted Jan 06, 2015 09:17 AM

    Hi Lucd,

    I have tried like below and all VM's started cloning from CSV and more over it is not accepting the Varaiables from CSV File and getting error unable to get Name "$_.cluster". Please suggest.

    $MaxClones = 3

    $CSV = "C:\users\$env:username\Linux.csv"

    $nvm = Import-CSV $CSV -Useculture

    $nvm | %{

    New-VM -Name $_.Name -vm $(Get-Cluster $_.cluster | Get-ResourcePool $_.SVMLocation | get-vm $_.SourceVM) -VMHost $(Get-Cluster $_.cluster | Get-VMHost -state "connected" | Get-Random) -ResourcePool $(Get-Cluster $_.cluster | Get-ResourcePool $_.rp) -datastore $(Get-Cluster $_.cluster | Get-DataStore $_.ds) -Notes $_.Notes -RunAsync

    $CurrentClones = Get-Job -State Running | Measure-Object | Select -ExpandProperty Count

      while($CurrentClones -ge $MaxClones)

      {

      sleep 30

      $CurrentClones = 0

      }

    }



  • 24.  RE: Create VM using PowerCLI and csv file

    Posted Jan 06, 2015 09:30 AM

    Do you have a column named Cluster in the CSV file ?



  • 25.  RE: Create VM using PowerCLI and csv file

    Posted Jan 06, 2015 10:13 AM

    Yes Lucd, It's column name please find the CSV in attachment.



  • 26.  RE: Create VM using PowerCLI and csv file

    Posted Jan 06, 2015 10:41 AM

    Does the following display the properties correctly ?

    Import-CSV $CSV -Useculture | Select Name,Cluster

    Could you perhaps also include a screenshot of the error message you are getting ?



  • 27.  RE: Create VM using PowerCLI and csv file

    Posted Jan 06, 2015 11:26 AM

    Hi Lucd,

    Please see the attachments and suggest.



  • 28.  RE: Create VM using PowerCLI and csv file

    Posted Jan 06, 2015 12:08 PM

    I overlooked it as well, you were using the pipeline variable $_, but that was not the row from the CSV file anymore.

    Try like this

    $MaxClones = 3

    $CSV = "C:\users\$env:username\Linux.csv"

    $nvm = Import-CSV $CSV -Useculture

    foreach($row in $nvm){

        New-VM -Name $row.Name`

            -vm $(Get-Cluster $row.cluster | Get-ResourcePool $row.SVMLocation | get-vm $row.SourceVM)`

            -VMHost $(Get-Cluster $row.cluster | Get-VMHost -state "connected" | Get-Random)`

            -ResourcePool $(Get-Cluster $row.cluster | Get-ResourcePool $row.rp)`

            -datastore $(Get-Cluster $row.cluster | Get-DataStore $row.ds)`

            -Notes $row.Notes -RunAsync

        $CurrentClones = Get-Job -State Running | Measure-Object | Select -ExpandProperty Count

       

        while($CurrentClones -ge $MaxClones)

        {

            sleep 30

            $CurrentClones = Get-Job -State Running | Measure-Object | Select -ExpandProperty Count

        }

    }



  • 29.  RE: Create VM using PowerCLI and csv file

    Posted Jan 06, 2015 12:23 PM

    Hi Lucd,

    I have kept 3 VM's in CSV and executed below script and still 3 vm's started cloning at a time and script execution got completed once the final VM clone has started. Please find the attachment.



  • 30.  RE: Create VM using PowerCLI and csv file

    Posted Jan 06, 2015 01:28 PM

    Try displaying the $currentClones value inside the While loop.



  • 31.  RE: Create VM using PowerCLI and csv file

    Posted Jan 07, 2015 11:33 AM

    Hi Lucd,

    I have tried passing $currentClones value in while loop and still 3 VM's are cloning at a time as I have limited to 2 in CSV. Please find attachment.



  • 32.  RE: Create VM using PowerCLI and csv file

    Posted Jan 07, 2015 12:01 PM

    Why are you setting the value of $CurrentClones to 0 inside the loop ?

    That way the loop will never wait when more than 2 clones are running



  • 33.  RE: Create VM using PowerCLI and csv file

    Posted Jan 07, 2015 12:14 PM

    I though it displaying $currentclones in while loop is passing $currentclones =0 , If I have applied wrongly, Please suggest.



  • 34.  RE: Create VM using PowerCLI and csv file

    Posted Jan 07, 2015 12:24 PM

    Try the following, it will display the value of $CurrentClones

    $MaxClones = 3

    $CSV = "C:\users\$env:username\Linux.csv"

    $nvm = Import-CSV $CSV -Useculture

    foreach($row in $nvm){

        New-VM -Name $row.Name`

            -vm $(Get-Cluster $row.cluster | Get-ResourcePool $row.SVMLocation | get-vm $row.SourceVM)`

            -VMHost $(Get-Cluster $row.cluster | Get-VMHost -state "connected" | Get-Random)`

            -ResourcePool $(Get-Cluster $row.cluster | Get-ResourcePool $row.rp)`

            -datastore $(Get-Cluster $row.cluster | Get-DataStore $row.ds)`

            -Notes $row.Notes -RunAsync

        $CurrentClones = Get-Job -State Running | Measure-Object | Select -ExpandProperty Count

      

        Write-Output "Current: $($CurrentClones)   Max: $($MaxClones)"

        while($CurrentClones -ge $MaxClones)

        {

            Write-Output "In loop: Current: $($CurrentClones)   Max: $($MaxClones)"

            sleep 30

            $CurrentClones = Get-Job -State Running | Measure-Object | Select -ExpandProperty Count

        }



  • 35.  RE: Create VM using PowerCLI and csv file

    Posted Jan 07, 2015 12:29 PM

    It is showing $currentClones as 0, Please find attachment.



  • 36.  RE: Create VM using PowerCLI and csv file

    Posted Jan 07, 2015 01:01 PM

    I overlooked that, it should be Get-Task instead of Get-Job.

    $MaxClones = 3

    $CSV = "C:\users\$env:username\Linux.csv"

    $nvm = Import-CSV $CSV -Useculture

    foreach($row in $nvm){

        New-VM -Name $row.Name`

            -vm $(Get-Cluster $row.cluster | Get-ResourcePool $row.SVMLocation | get-vm $row.SourceVM)`

            -VMHost $(Get-Cluster $row.cluster | Get-VMHost -state "connected" | Get-Random)`

            -ResourcePool $(Get-Cluster $row.cluster | Get-ResourcePool $row.rp)`

            -datastore $(Get-Cluster $row.cluster | Get-DataStore $row.ds)`

            -Notes $row.Notes -RunAsync

        $CurrentClones = Get-Task -Status Running | Measure-Object | Select -ExpandProperty Count

      

        while($CurrentClones -ge $MaxClones)

        {

            sleep 30

            $CurrentClones = Get-Task -Status Running | Measure-Object | Select -ExpandProperty Count

        }



  • 37.  RE: Create VM using PowerCLI and csv file

    Posted Jan 08, 2015 11:43 AM

    Hi Lucd,

    I have passed 3 VM's for cloning and limited to 2.

    Script is limiting the Clone based on total number of Tasks happening on VI, I have observed while vMotion is happening at that time also script is going to sleep mode until unless that migration is completed. Please suggest.



  • 38.  RE: Create VM using PowerCLI and csv file

    Posted Jan 08, 2015 01:01 PM

    That is because the script is only looking for active tasks that have the status "running".

    The test should be made more specific, you should test besides the status also on the name of the task.

    Can you do a Get-Task while these clones are running ?

    That should allow us to make the test more specific.



  • 39.  RE: Create VM using PowerCLI and csv file

    Posted Jan 09, 2015 08:30 AM

    Hi Lucd,

    After adding taskname in script it is working fine, but I hope if another Engineer has opened another PowerCLI console and started VM Cloning using same script at that time get-task will be returning total tasks executing in vSphere environment instead of executing in loop, is there any way to overcome this issue.

    Get-Task is returning all success, Error, Running in vSphere Client Recent Taks. Please suggest.



  • 40.  RE: Create VM using PowerCLI and csv file

    Posted Jan 09, 2015 09:03 AM

    You can test on the Name and the status of the task

    $CurrentClones = Get-Task -Status Running | where {$_.Name -match 'CloneVM_Task'} |

        Measure-Object | Select -ExpandProperty Count

    Another solution is to keep track of the Task IDs and only check the status of those you submitted.

    Something like this

    $MaxClones = 3

    $CSV = "C:\users\$env:username\Linux.csv"

    $nvm = Import-CSV $CSV -Useculture

    $idTab = @()

    foreach($row in $nvm){

        $idTab += New-VM -Name $row.Name`

            -vm $(Get-Cluster $row.cluster | Get-ResourcePool $row.SVMLocation | get-vm $row.SourceVM)`

            -VMHost $(Get-Cluster $row.cluster | Get-VMHost -state "connected" | Get-Random)`

            -ResourcePool $(Get-Cluster $row.cluster | Get-ResourcePool $row.rp)`

            -datastore $(Get-Cluster $row.cluster | Get-DataStore $row.ds)`

            -Notes $row.Notes -RunAsync | Select -ExpandProperty Id

        $CurrentClones = Get-Task -Status Running |

            where {$idTab -contains $_.Id} |

            Measure-Object | Select -ExpandProperty Count

     

        while($CurrentClones -ge $MaxClones)

        {

            sleep 30

            $CurrentClones = Get-Task -Status Running |

                where {$idTab -contains $_.Id} |

                Measure-Object | Select -ExpandProperty Count

        }

    }  



  • 41.  RE: Create VM using PowerCLI and csv file

    Posted Jan 09, 2015 09:22 AM

    Hi Lucd,

    I have Posted the Screenshot with Status and Name of the task looping in script and it is working fine, and I will check with this Task ID created by New-vm and get back to you. Thanks a lot.



  • 42.  RE: Create VM using PowerCLI and csv file

    Posted Jan 09, 2015 01:08 PM

    Hi Lucd,

    Script is working fine !!! is it possible to display like VM1 is deployed, VM2 is deploying. Please suggest.



  • 43.  RE: Create VM using PowerCLI and csv file

    Posted Jan 09, 2015 02:00 PM

    Sure, try this

    $MaxClones = 3

    $CSV = "C:\users\$env:username\Linux.csv"

    $nvm = Import-CSV $CSV -Useculture

    $idTab = @()

    foreach($row in $nvm){

        $idTab += New-VM -Name $row.Name`

            -vm $(Get-Cluster $row.cluster | Get-ResourcePool $row.SVMLocation | get-vm $row.SourceVM)`

            -VMHost $(Get-Cluster $row.cluster | Get-VMHost -state "connected" | Get-Random)`

            -ResourcePool $(Get-Cluster $row.cluster | Get-ResourcePool $row.rp)`

            -datastore $(Get-Cluster $row.cluster | Get-DataStore $row.ds)`

            -Notes $row.Notes -RunAsync | Select -ExpandProperty Id

        $CurrentClones = Get-Task -Status Running |

            where {$idTab -contains $_.Id} |

            Measure-Object | Select -ExpandProperty Count

        Write-Output "VM $($row.Name) is being deployed"

        while($CurrentClones -ge $MaxClones)

        {

            sleep 30

            $CurrentClones = Get-Task -Status Running |

                where {$idTab -contains $_.Id} |

                Measure-Object | Select -ExpandProperty Count

        }

    }

       



  • 44.  RE: Create VM using PowerCLI and csv file

    Posted Jan 12, 2015 06:05 AM

    Hi Lucd,

    Thanks for your support and below is the final script which I am going to use for multiple deployments.

    Is there any way that due to some problem if the command doesn't executed then It will generate a log in some path like C:\error.log

    Ex: VM1 is not cloned, VM2 CPU is not configured etc.

    Please suggest.

    $MaxClones = 3

    $CSV = "C:\users\$env:username\Linux.csv"

    $nvm = Import-CSV $CSV -Useculture

    $idTab = @()

    $nvm |

    %{

    $idTab += New-VM -Name $_.Name`

            -vm $(Get-Cluster $_.cluster | Get-ResourcePool $_.SVMLocation | get-vm $_.SourceVM)`

            -VMHost $(Get-Cluster $_.cluster | Get-VMHost -state "connected" | Get-Random)`

            -ResourcePool $(Get-Cluster $_.cluster | Get-ResourcePool $_.rp)`

            -datastore $(Get-Cluster $_.cluster | Get-DataStore $_.ds)`

            -Notes $_.Notes -RunAsync | Select -ExpandProperty Id

      $CurrentClones = Get-Task -Status Running |

            where {$idTab -contains $_.Id} |

            Measure-Object | Select -ExpandProperty Count

      Write-Output "$($_.Name) is deploying"

      Write-Output "In loop: Current: $($CurrentClones)   Max: $($MaxClones)"

      while($CurrentClones -ge $MaxClones)

      {

            sleep 30

     

      Write-Output "$($_.Name) is deploying"       

      Write-Output "In loop: Current: $($CurrentClones)   Max: $($MaxClones)"

      if($currentclones -eq $maxclones){

            $CurrentClones = Get-Task -Status Running |

            where {$idTab -contains $_.Id} |

            Measure-Object | Select -ExpandProperty Count

      }

    }  

    #Configuring CPU If values exists in CSV

    $nvm | %{ if($_.CPU -ne [string]$null) {Set-VM -VM $_.Name -NumCpu $_.Cpu -Confirm:$false  }}

    #Configuring Memory If values exists in CSV

    $nvm | %{ if($_.MGB -ne [string]$null) {Set-VM -VM $_.Name -MemoryGB $_.MGB -Confirm:$false }}

    #Adding HardDisk If values exists in CSV

    $nvm | %{ if($_.HDD -ne [string]$null) {New-HardDisk -VM $_.Name -CapacityGB $_.HDD -Persistence persistent -Confirm:$false }}

    #Configuring VLAN If values exists in CSV

    $nvm | %{ if($_.VLAN -ne [string]$null) {Get-VM $_.Name | Set-NetworkAdapter  -NetworkName "$_.VLAN" -Confirm:$false}}



  • 45.  RE: Create VM using PowerCLI and csv file

    Posted Dec 13, 2015 06:02 AM

    Hi

    Set-OSCustomizationNicMapping : 12/12/2015 9:54:21 PM    Set-OSCustomizationNicMapping        You must not provide

    Wins or Dns when you create NIC mapping for a customization spec with type 'linux'.

    At line:3 char:5

    +     Set-OSCustomizationNicMapping -IpMode UseStaticIP -IpAddress $_."IP Address" ...

    +     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

        + CategoryInfo          : InvalidArgument: (:) [Set-OSCustomizationNicMapping], ViError

        + FullyQualifiedErrorId : Core_NicMappingCmdletBase_ValidateParameters_LinuxAndWins,VMware.VimAutomation.ViCore.Cm

       dlets.Commands.SetOSCustomizationNicMapping

    Set-OSCustomizationNicMapping : 12/12/2015 9:54:21 PM    Set-OSCustomizationNicMapping        When the IpMode

    parameter is set to UseStaticIp, you must specify the IPAddress, Subnetmask, Dns(on Windows specs only), and

    DefaultGateway parameters.

    At line:3 char:5

    +     Set-OSCustomizationNicMapping -IpMode UseStaticIP -IpAddress $_."IP Address" ...

    +     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

        + CategoryInfo          : InvalidArgument: (:) [Set-OSCustomizationNicMapping], ViError

        + FullyQualifiedErrorId : Core_NicMappingCmdletBase_ValidateParameters_RequiredParametersSaticIp,VMware.VimAutomat

       ion.ViCore.Cmdlets.Commands.SetOSCustomizationNicMapping

    Here is my xls

    Server NameESX HostTemplateDatastoreCustomizationNumCpuIP AddressMemoryGBSubnetMaskDefaultGateway

    dns

    pls suggest



  • 46.  RE: Create VM using PowerCLI and csv file

    Posted Dec 13, 2015 06:06 AM

    Never mind, Thanks

    I saw your note

    For a Linux OS you can not specify the DNS parameter on the Set-OSCustomization cmdlet.

    First try leaving out the this DNS parameter



  • 47.  RE: Create VM using PowerCLI and csv file

    Posted May 03, 2017 04:26 PM

    I don't understand why there are two customization specs used: one from the .csv file ($_.Customization) and one defined as "$cust".  When i run this script I get an error  "could not find customization specification with name 'Test'.  When I change the script to use $_.Customization as the name in both places, the script runs. 

    What is the purpose of having the 2 specs?



  • 48.  RE: Create VM using PowerCLI and csv file

    Posted May 22, 2017 07:37 PM

    I agree, it doesn't make sense.

    Also, did you get this error in the output?

    oscustomizationspec doesn't seem to itself be depreciated.



  • 49.  RE: Create VM using PowerCLI and csv file

    Posted May 22, 2017 09:00 PM

    That is no error, it's a warning, telling you that this parameter might disappear in a future PowerCLI release.

    Start using the suggested parameter.