如何根据变量获取CSV列

问题描述

我正在尝试创建一个脚本,该脚本应该读取 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","col3"

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

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

如果你想要一个完整的 csv 示例:

#columns to select
$myarray= "col1","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
}