首页 > 解决方案 > Powershell Script to parse selected information from txt file and output to csv

问题描述

checked the FAQ's on parsing data and have tried a couple ideas but nothing is working the way I need it. I need a suggestion on how to build a PS script that will read the following information in my .txt file and output only selected information to .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 file will contain three columns:

Store    Install     Date

Need PS script to grab the store # (0009) and add it under the Store column. If that line contains "included with your TV purchase" under the install column add True if not add False and then add the date in date column.

Code try from comment

$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 
    } 
  }

标签: powershelltext-parsing

解决方案


As suggested

  • choose a regular expression that matches your requrements (see regex101.com)
  • iterate the matches and compare the ,matched text
  • generate a [PSCustomObject] for your csv

## Q:\Test\2018\10\17\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

Sample output:

> Q:\Test\2018\10\17\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

推荐阅读