I am trying to create a script that should read CSV
column-based array variables to execute some analysis on them. I have created a script that runs fine if I use the manual array column reading which is way too hard for a huge file. Is there a way to make it work when I use variables from an array?
Below is a part of the script which I am having trouble with:
$myarray= "col1", "col2", "col3"
$mycsv=import-csv e:\text.csv
$mycsv.$myarray[0] # this does not work
$mycsv.col1 # this works fine
PowerShell allows you to use expressions as property names.
In your case, because the expression involves an array subscript, you need to enclose it in ()
, the grouping operator :
$mycsv.($myarray[0])
A simplified example:
$myarray= "col1", "col2", "col3"
$obj = [pscustomobject] @{ col1 = 'foo' }
$obj.($myarray[0]) # -> 'foo'
Other solution:
$myarray= "col1", "col2", "col3"
$obj = [pscustomobject] @{ col1 = 'foo' }
$obj.psobject.Properties[$myarray[0]].Value
If you want a complet example for csv:
#columns to select
$myarray= "col1", "col2", "col3"
#import csv
$Rows = import-csv "e:\text.csv" #csv have colum Nom, Prenom, age, autre
#take columns list into $myarray and used into csv
$PropertyToTake=$Rows | Get-Member -MemberType NoteProperty | where Name -in $myarray
#loop on all rows csv and extract only columns values of myarray
$Rows | %{
$CurrentRow=$_
#create empty object
$Object=[pscustomobject]@{}
#Add properties to object with property name and value of csv
$PropertyToTake | %{Add-Member -InputObject $Object -MemberType NoteProperty -Name $_.Name -Value $CurrentRow.psobject.Properties[$_.Name].Value }
#send object on output
$Object
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.