Search code examples
powershellcsvpowercli

Add a variable in front of values of certain columns in a CSV


I'am currently trying to create a simple Import-Csv to clone vm-guests from a template to a esx host in vcenter.

Before I start the cloning I want to ask for the name of the site the vm-guests will belong to. The name of the site is part of the name the vm-guest will have, and also part of the foldername, the guest will be put into.

Connect-VIServer -Server vcenter.localdomain.com -user *

$Site = Read-Host "What is the name of the Site you want to install (i.e. Site01)?"

Import-Csv "C:\guests.csv" -UseCulture | %{
New-vm -Name  $_."Server Name" -VMhost $_."ESX Host" -Template $_.Template -Datastore $_.Datastore  -Location $_.Folder
}

How/Where do I put in the variable $Site to have it in front of $_."Server Name" and $_.Folder?


Solution

  • You could use a format string:

    Connect-VIServer -Server vcenter.localdomain.com -user *
    
    $Site = Read-Host "What is the name of the Site you want to install (i.e. Site01)?"
    
    Import-Csv "C:\guests.csv" -UseCulture | %{
    New-vm -Name ('{0}{1}' -f $Site, $_."Server Name") -VMhost $_."ESX Host" -Template $_.Template -Datastore $_.Datastore  -Location ('{0}{1}' -f $Site, $_.Folder)
    }