I'm trying to read a csv file and store its data into variables that I will use for Powershell scripts. I managed to read the file by doing the following command:
$csv = Import-Csv C:\Users\[...]\Documents\ipaddresses.csv -delimiter "|"
$csv
The output looks like this:
IP Name
-- ----
165.XX.XX.1 n1
165.XX.XX.2 n2
165.XX.XX.3 n3
165.XX.XX.4 n4
165.XX.XX.5 n5
165.XX.XX.6 n6
The idea is that I could create 6 variables each like:
$Name = $IP
However, when I try to loop the objects of the $csv variable and store them into arrays like this:
foreach($item in $csv){
IP = $($item.IP)
Name = $($item.Name)
}
It returns me empty arrays. How do I fix this?
$preceding their names. So at a minimum, you must have$IP = $line.IPand$Name = $line.Name. Even with correct syntax, your variables in this example would get overwritten during each iteration of your loop. That would mean that any operation that depends on them needs to happen within that loop. I would not use$itemas a variable name as I am not sure if that could cause a conflict in certain cases with reserved/automatic variables.$csvdoes already contain all the information you could want. If you need to maintain access to data throughout your code, specifically outside of your loops, you can reference specific lines with indexes ($csv[3]or$csv[2].IP). You can also access properties from the whole array ($csv.Nameor$csv.IP). Also, variable assignment typically suppresses success stream output. So you would need to explicitly ask for the assigned value by typing the variable name$IPor$Namewithout assignment.$csvat all after you do theImport-Csv? If all of your data including the headers is not truly separated by |, then using the-Delimiter "|"will result in your situation. If the CSV file has commas rather than |, don't use-Delimiter. That switch tells PowerShell how your data is already separated and not how you want it to be separated after you import it.