0

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++

}
Enigma
  • 123
  • 1
  • 13
  • [Don't use the `-Variable` cmdlets for dynamic variable names!](https://stackoverflow.com/a/68830451/1701026) – iRon Nov 20 '21 at 13:49
  • `$Var = '.\fileOne.csv', '.\fileTwo.csv', '.\fileThree.csv'`. Now, `$Var[1]` contains `'.\fileTwo.csv'` – iRon Nov 20 '21 at 18:20

1 Answers1

0

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.

Santiago Squarzon
  • 41,465
  • 5
  • 14
  • 37
  • Hi Santiago.. sorry for the confusion.. i am exporting a csv file with filename like file1,file2,file 3 in the loop from variable $varname.csv. During the loop i want to import each csv to a variable like $var1=file1, $var2 = file2, $var3 = file3 and so on. – Enigma Nov 20 '21 at 06:23
  • Hi Santiago.. the key is to assign the ```$csv = Import-Csv path/to/csv.csv```.. much appreciated – Enigma Nov 20 '21 at 07:35