Search code examples
powershellpowershell-4.0

Set Variable assigning Import-csv value


I am trying to assign import-csv value to a set variable under a loop so i can work with the csv file on variable $var1, $var2,$var3 like..

$i = 1
{
$result = Export-Csv -Path ".\$varname.csv" -NoTypeInformation 
New-Variable -Name "var$i" -Value "import-csv -Path .\$varname.csv"
Get-Variable -Name "var$i" -ValueOnly
$i++

}

Solution

  • Your question is missing the actual problem you need help with or what is failing.
    I see you're using Export-Csv, I would assume you meant to use Import-Csv.

    If you want to store the content of a CSV and set that content to dynamically created variables, this is how you can do it:

    $numberOfvariables = 5
    $csv = Import-Csv path/to/csv.csv
    
    0..$numberOfvariables | ForEach-Object {
        Set-Variable -Name var$_ -Value $csv
    }
    

    Note that, I'm using Set-Variable instead of New-Variable, both serve the same purpose in this example however if you re-run the script without removing the variables you would get the exception A variable with name 'var' already exists. using New-Variable unless you use the -Force switch.