Search code examples
windowspowershellvspherevcenter

How to assign variables to a Powershell script from a file?


I am trying to deploy 20 vms in vcenter using vsphere powerCLI, instead of prompting for vmname/hostname again and again or passing params for 20 times I am looking for passing the 20 vm names from a file.


Solution

  • You can do this in a quick one-liner, create a csv file with the headings and values you want to use like so:

    VMName,Hostname
    VM001,Server01
    VM002,Server02
    VM003,Server03
    

    Then use Import-CSV and Foreach to loop through the file and run your command (New-VM used as an example) with the fields from each row.

    Import-Csv C:\folder\file.csv | Foreach { New-VM -VMName $_.VMName -Hostname $_.Hostname }