Powershell 脚本从 txt 文件中解析选定的信息并输出到 csv

Powershell Script to parse selected information from txt file and output to csv

查看了有关解析数据的常见问题解答并尝试了一些想法,但没有任何效果符合我的需要。我需要有关如何构建 PS 脚本的建议,该脚本将读取我的 .txt 文件中的以下信息并仅将选定的信息输出到 .csv

eamoptns.ftr.0009: LoyaltyPrint3 = "     included with your TV purchase"
eamoptns.ftr.0010: LoyaltyPrint3 = "     included with your TV purchase"

Grand Total: 2 match(es) found.

CSV 文件将包含三列:

Store    Install     Date

需要 PS 脚本来获取商店 # (0009) 并将其添加到商店列下。如果该行在安装列下包含 "included with your TV purchase",则添加 True 如果不添加 False,然后在日期列中添加日期。

来自评论的代码尝试

$PSRoot = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition 
Get-ChildItem $PSRoot -Filter "*Results.txt" | 
  Where-Object { $_.Attributes -ne "Directory" } | ForEach-Object { 
    If (Get-Content $_.FullName | Select-String -Pattern "included with your TV purchase") { 
      New-Object -TypeName PSCustomObject -Property @{
        Club = $A
        Install = $B 
        Date = $C
      } | Export-CSV -Path $PSRoot\Test.csv -Append 
    } 
  }

按照建议

  • 选择符合您要求的正则表达式(参见 regex101.com
  • 迭代匹配并比较匹配的文本
  • 为您的 csv 生成 [PSCustomObject]

## Q:\Test18\SO_52857274.ps1
$RE = [RegEx]'^.*?\.(\d{4}):[^"]+"\s*(included with your TV purchase|.*)"$'

$CSV = Select-String '.\my.txt' -Pattern $RE | ForEach-Object {
    IF ($_.Matches.Groups[2].Value -eq 'included with your TV purchase'){
        $Install = $True
    } else {
        $Install = $False
    }
    [PSCustomObject]@{
        Store   = $_.Matches.Groups[1].Value
        Install = $Install
        Date    = (Get-Date).Date
    }
}
$CSV
# $CSV | Export-CSV '.\my.csv' -NoTypeInformation

示例输出:

> Q:\Test18\SO_52857274.ps1

Store Install Date
----- ------- ----
0009     True 2018-10-17 00:00:00
0010     True 2018-10-17 00:00:00
0010    False 2018-10-17 00:00:00