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. I am already selecting my CSV fields as I import them, so would like to use something akin to the following :
$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
. 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.
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.
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.