I have a simple CSV file with 3 columns, and a header for row#1 (Name, Department, Region). I run the following command in Powershell but am not getting the values for each column into their respective arrays. I was hoping to import all cell values under Name column into a $name array, $department array and $region array. So far no luck.
When i run the command $csv[2], it shows me the header and then the 3 values for Name, department and region. Something like this below. But if i run just $name, it does not show me anything, i was expecting a list of all names one line at a time. What am i doing wrong please? Thanks a bunch
What version of Powershell are you running? $csv.Name is an implicit loop, which was introduced in version 3. Another simple method that should work regardless of the version is -ExpandProperty:
$obj = @()
$obj += [pscustomobject]@{
Name = 'Rob'
Department = 'IT'
Region = 'Florida'
}
$obj += [pscustomobject]@{
Name = 'James'
Department = 'Engineering'
Region = 'Arizona'
}
#Version 3 or higher
$obj.Name
#All versions
$obj | Select-Object -ExpandProperty Name
#Another option is an explicit loop
$obj | foreach{$_.Name}
Output:
PS C:\Users\Rob> $obj.Name
Rob
James
PS C:\Users\Rob> $obj | Select-Object -ExpandProperty Name
Rob
James
PS C:\Users\Rob> $obj | foreach{$_.Name}
Rob
James
Hi Rob. Thanks for your reply. I’m running PS version 5.1. I’m a bit confused from your reply. I have all the data already in the CSV file and would just like to import the 3 columns into 3 unique arrays in Powershell. Your code seems to show them being manually added one row at a time? Please correct me if i’m wrong. Can you tell me what i’m doing wrong not to get the 3 columns into 3 arrays? Thank you again sir.
Nevermind I figured out what you did. I entered $csv | select -expandproperty Name and it worked. Thank you Rob
[quote quote=120603]Hi Rob. Thanks for your reply. I’m running PS version 5.1. I’m a bit confused from your reply. I have all the data already in the CSV file and would just like to import the 3 columns into 3 unique arrays in Powershell. Your code seems to show them being manually added one row at a time? Please correct me if i’m wrong. Can you tell me what i’m doing wrong not to get the 3 columns into 3 arrays? Thank you again sir.
Powershell does a lot of things implicitly for you without asking for.
If you import some data from a CSV file you actually already have three single arrays: