如何根据变量获取CSV列

How to get CSV column based on variable

我正在尝试创建一个脚本,该脚本应该读取 CSV 基于列的数组变量以对它们执行一些分析。我创建了一个脚本,如果我使用手动数组列读取,该脚本运行良好,这对于一个大文件来说太难了。当我使用数组中的变量时,有没有办法让它工作?

下面是我遇到问题的部分脚本:

$myarray= "col1", "col2", "col3"
$mycsv=import-csv e:\text.csv
$mycsv.$myarray[0] # this does not work
$mycsv.col1        # this works fine

PowerShell 允许您使用 表达式 作为 属性 名称。

在你的例子中,因为表达式涉及数组下标,所以你需要将它括在()中,grouping operator:

$mycsv.($myarray[0])

一个简化的例子:

$myarray= "col1", "col2", "col3"

$obj = [pscustomobject] @{ col1 = 'foo' }

$obj.($myarray[0]) # -> 'foo'

其他解决方案:

$myarray= "col1", "col2", "col3"

$obj = [pscustomobject] @{ col1 = 'foo' }

$obj.psobject.Properties[$myarray[0]].Value

如果您想要一个完整的 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
}