powershell - 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
}
}
解决方案
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
推荐阅读
- vaadin - 如何在 vaadin-grid 中设置标题样式
- java - 为什么以及如何编译这个奇怪的方法返回类型?
- android - 使用 Firestore 时避免相同的聊天
- javascript - 如何使 jQuery 构造函数属性全局可见
- asp.net-core - 在不同的服务器上设置 Web.MVC 和主机站点
- cordova - Ionic 应用程序在 android 上运行,但在 iOS 上出现多个插件的 plugin_not_installed 错误
- c# - 如何解决 SharpZipBaseException '标头校验和非法'?
- google-apps-script - 根据谷歌表格信息创建个性化的谷歌表单
- javascript - 这些异步/等待代码之间有区别吗?
- html - 固定表头没有和列对齐