创建列并将数组内容插入列中。

时间:2019-01-02 19:59:51

标签: powershell

我正在读取CSV文件,之后使用-match查找所需的模式。现在,我所有的匹配项都放在一个名为$ results的变量中。接下来,我想创建一个新列,并将$ results的内容插入该列。我已经坚持了一段时间,尝试使用for循环,forEach循环,if语句,但似乎无法获得所需的结果。我是Powershell的新手,所以我可能缺少明显的东西。任何帮助是极大的赞赏!   这是我的代码:

 $target = "This is the path to the .CSV file"
 $pattern = '(V-\d*)'

 $TestFile = (Get-Content $target) 

 $results = $TestFile | Select-String $pattern -AllMatches 
 $results.Matches.Value 



 #$TestFile -replace '(V-\d*)',' '

 $NewFile = ConvertFrom-Csv $TestFile|  Select-Object *,@{Name='Generic 
  Header';Expression={"Unsure of how to input data here without having all 
  data in same row"}}|export-csv ' Path for Exporting New .CSV file' -notype

2 个答案:

答案 0 :(得分:1)

在前面的不同列中使用模式采样csv文件

> import-csv  .\SO_54012419.csv

col1  col2  col3
----  ----  ----
foo   bar   V-123
V-345 foo   bar
bar   V-789 foo

运行此脚本:

$target  = ".\SO_54012419.CSV"
$pattern = '(V-\d*)'

$csvdata = Import-Csv $target | Select-Object *,Result

foreach($row in $csvdata){
  if ($row -match $pattern){
    $Row.Result = $Matches[1]
  }
}

$csvdata
$csvdata | Export-Csv 'Path for Exporting New.CSV' -NoTypeInformation

及之后:

col1  col2  col3  Result
----  ----  ----  ------
foo   bar   V-123 V-123
V-345 foo   bar   V-345
bar   V-789 foo   V-789

答案 1 :(得分:0)

如果我正确理解了这个问题,我认为应该这样做:

$target  = "This is the path to the .CSV file"
$pattern = '(V-\d*)'
$column  = 'The name of the column to perform the regex match on'

# Read the input file as array of PSCustomObjects
$content = Import-Csv $target

# Do a foreach loop on each of the objects in the $content array
# and perform the regex -match on it. Add a new property (column) to every
# object in the array with the result of your regex match. 
# Add an empty string if no match was found.
foreach ($item in $content) {
    if ($item.$column -match $pattern) {
        $item | Add-Member -MemberType NoteProperty -Name 'Result' -Value $matches[1]
    }
    else {
        $item | Add-Member -MemberType NoteProperty -Name 'Result' -Value ''
    }
}

# now use Export-Csv to write the new file complete with the new 'Result' header
$content | Export-Csv 'Path for Exporting New .CSV file' -NoTypeInformation