[英]PowerShell - Dynamically Combine CSV Columns
I have a CSV file that I'm restructuring using PowerShell and I want to combine values across a number of fields that have names matched using a wildcard. 我有一个正在使用PowerShell进行重组的CSV文件,并且我想在多个使用通配符匹配名称的字段中组合值。 I am already selecting my CSV fields as I import them, so would like to use something akin to the following :
导入它们时,我已经选择了CSV字段,因此想使用类似于以下内容的内容:
$c4 = @{n="Grouped";e={$_.C1+$_.C2+$_.C3}}
$csv = import-csv $incsv | select $c4
This works, but I am trying to find a way of dynamically creating the e
expression in $c4
. 这可行,但是我试图找到一种在
$c4
中动态创建e
表达式的方法。 I am able to build an array of column names (in this example, to include C1 to C3), but can't figure out how to build the expression using this. 我能够建立一个列名数组(在此示例中,包括C1到C3),但无法弄清楚如何使用此列来构建表达式。
I have a couple of limitations: 我有两个限制:
Any help is greatly appreciated! 任何帮助是极大的赞赏!
Thanks. 谢谢。
You can create a scriptblock from a string that you've composed from your field names eg: 您可以使用由字段名称组成的字符串创建脚本块,例如:
$sb = [scriptblock]::create("`$_.C1+`$_.C2+`$_.C3")
$c4 = @{n="Grouped";e=$sb}
With a string you can use looping and various constructs to create your string and then pass that to [scriptblock]::create()
to get back a scriptblock that you can use for the Expression part of the Select hashtable. 使用字符串,您可以使用循环和各种构造来创建您的字符串,然后将其传递给
[scriptblock]::create()
以获取可用于Select哈希表的Expression部分的脚本块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.