通过动态变量名称获取变量 [英] Get a variable by dynamic variable name
问题描述
如何使用动态便笺属性名称访问从CSV文件导入的数据?也就是说,事先不知道名称.它们确实与模式匹配,并且在脚本运行时从CSV文件中提取.
How does one access data imported from a CSV file by using dynamic note property names? That is, one doesn't know the colunm names beforehand. They do match a pattern and are extracted from the CSV file when the script runs.
例如,考虑一个CSV文件:
As for an example, consider a CSV file:
"Header 1","Header A","Header 3","Header B"
0,0,0,0
1,2,3,4
5,6,7,8
我只想提取以字母结尾的列.为此,我阅读标题行并使用正则表达式提取名称,
I'd like to extract only columns that end with a letter. To do this, I read the header row and extract names with a regex like so,
$reader = new-object IO.StreamReader("C:\tmp\data.csv")
$line = $reader.ReadLine()
$headers = @()
$line.Split(",") | % {
$m = [regex]::match($_, '("Header [A-Z]")')
if($m.Success) { $headers += $m.value } }
这将获得我关心的所有列名称:
This will get all the column names I care about:
"Header A"
"Header B"
现在,要访问CSV文件,我将其导入为
Now, to access a CSV file I import it like so,
$csvData = import-csv "C:\tmp\data.csv"
导入CSV将创建一个自定义对象,该对象具有与标题行相同的属性.可以像这样通过NoteProperty名称访问字段,
Import-CSV will create a custom object that has properties as per the header row. One can access the fields by NoteProperty names like so,
$csvData | % { $_."Header A" } # Works fine
这显然需要事先知道列名.我想使用提取并存储到$headers
中的colunn名称.我该怎么办?
This obviously requires one to know the column name in advance. I'd like to use colunn names I extracted and stored into the $headers
. How would I do that?
到目前为止我已经尝试过的一些事情
Some things I've tried so far
$csvData | % { $_.$headers[0] } # Error: Cannot index into a null array.
$csvData | % { $np = $headers[0]; $_.$np } # Doesn't print anything.
$csvData | % { $_.$($headers[0]) } # Doesn't print anything.
我可以像这样更改脚本,以便它将编写另一个知道列名的脚本.那是我唯一的解决方案吗?
I could change the script like so it will write another a script that does know the column names. Is that my only solution?
推荐答案
我想到的第一件事(也是唯一的一个……对不起)是:
the first thing ( and the only one... sorry) that came in my mind is:
$csvData | % { $_.$(( $csvData | gm | ? { $_.membertype -eq "noteproperty"} )[0].name) }
获取第一个的列值和
$csvData | % { $_.$(( $csvData | gm | ? { $_.membertype -eq "noteproperty"} )[1].name) }
对于第二列,依此类推....
for second column and so on....
这是您需要的吗?
这篇关于通过动态变量名称获取变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!