我有一项任务,没有一种简单的方法将一些数据解析为正确的格式。我的文本文件是以下格式的
#N Last Name: Joe
#D First Name: Doe
#P Middle Name: A
Some Data:
#C ID Number: (1) 12345
#S Status: (1) Active
#N Last Name: Jane
#D First Name: Doee
#P Middle Name:
Some Data:
#C ID Number: (1) 11111
#S Status: (1) Active
ID Number: (2) 1231
Status: (2) Active
这是我试图使用的代码。
$A = Select-String -Pattern "#N" MYFILE.txt;
$B = Select-String -Pattern "#D" MYFILE.txt;
$C = Select-String -Pattern "#P" MYFILE.txt;
$D = Select-String -Pattern "#C" MYFILE.txt;
$E = Select-String -Pattern "#S" MYFILE.txt;
$wrapper = New-Object PSObject -Property @{ FirstColumn = $A; SecondColumn = $B; ThirdColumn = $C; FourthColumn = $D; FifthColumn = $E }
Export-Csv -InputObject $wrapper -Path .output.csv -NoTypeInformation
这就是我得到的结果
"SecondColumn","ThirdColumn","FifthColumn","FourthColumn","FirstColumn"
"System.Object[]","System.Object[]","System.Object[]","System.Object[]","System.Object[]"
我正在寻找的输出是#N、 #D,#P,#C,#S
Joe, Doe, A, 12345, Active
Jane, Doee, , 11111, Active
我们非常感谢您的帮助。
这里有另一种解析数据块的方法。我更改了用户信息,使其更清楚地显示发生了什么。[grin]
它的作用。。。
- 创建一个多行字符串来使用
当准备好实际执行此操作时,用对Get-Content -Raw
的调用替换整个#region/#endregion
块 - 定义用户数据块之间的分隔符
在这种情况下,它是2个换行符-一个在最后一个数据行的末尾,一个用于空行 - 将单个多行字符串拆分为多个这样的字符串
- 遍历生成的文本块
- 初始化用于生成PSCO的$Vars
- 将文本块拆分为文本行
- 过滤掉任何不以
#
、字母和最后一个空格开头的行 - 遍历其余行
- 在每行的第2个字符上运行
switch
- 当它匹配其中一个代码字母时,解析行&设置等效$Var的值
- 完成对当前字符串集的迭代
- 构建一个
[PSCustomObject]
来保存值 - 将其发送到
$Result
集合 - 完成文本块的迭代[外部
foreach
] - 在屏幕上显示集合
- 将集合保存到CSV
如果您想从CSV中删除引号,请不要
[grin]如果您必须冒破坏CSV的风险,那么您可以使用Get-Content
从文件中加载行,并将引号替换为空。
代码。。。
#region >>> fake reading in a text file as a single multiline string
# in real life, use "Get-Content -Raw"
$InStuff = @'
#N Last Name: ALast
#D First Name: AFirst
#P Middle Name: AMid
Some Data:
#C ID Number: (1) 11111
#S Status: (1) Active
#N Last Name: BLast
#D First Name: BFirst
#P Middle Name:
Some Data:
#C ID Number: (1) 22222
#S Status: (1) Active
ID Number: (2) 1231
Status: (2) Active
'@
#endregion >>> fake reading in a text file as a single multiline string
$BlockDelim = ([System.Environment]::NewLine) * 2
$Result = foreach ($Block in ($InStuff -split $BlockDelim))
{
# initialize stuff to $Null
# this handles non-matches [such as a missing middle name]
$FirstName = $MidName = $LastName = $IdNumber = $Status = $Null
# the "-match" filters for lines that start with a "#", a single letter, and a space
foreach ($Line in ($Block -split [System.Environment]::NewLine -match '^#w '))
{
switch ($Line[1])
{
'N' {
$LastName = $Line.Split(':')[-1].Trim()
break
}
'D' {
$FirstName = $Line.Split(':')[-1].Trim()
break
}
'P' {
$MidName = $Line.Split(':')[-1].Trim()
break
}
'C' {
$IdNumber = $Line.Split(':')[-1].Trim().Split(' ')[-1].Trim()
break
}
'S' {
$Status = $Line.Split(':')[-1].Trim().Split(' ')[-1].Trim()
break
}
} # end >>> switch ($Line[1])
} # end >>> foreach ($Line in ($Block -split [System.Environment]::NewLine))
# create a custom object and send it out to the collection
[PSCustomObject]@{
FirstName = $FirstName
LastName = $LastName
MidName = $MidName
IdNumber = $IdNumber
Status = $Status
}
} # end >>> foreach ($Block in ($InStuff -split $BlockDelim))
# display on screen
$Result
# send to a CSV file
$Result |
Export-Csv -LiteralPath "$env:TEMPVeebster_ParsedResult.csv" -NoTypeInformation
屏幕上的输出。。。
FirstName : AFirst
LastName : ALast
MidName : AMid
IdNumber : 11111
Status : Active
FirstName : BFirst
LastName : BLast
MidName :
IdNumber : 22222
Status : Active
CSV文件的内容。。。
"FirstName","LastName","MidName","IdNumber","Status"
"AFirst","ALast","AMid","11111","Active"
"BFirst","BLast","","22222","Active"
请注意,没有错误检测或错误处理。[grin]
这里还有另一个建议。我建议使用ConvertFrom字符串。
首先我们要做一个模板,我在你的样本数据中考虑了两行垃圾。我真的希望这是一个打字错误/抄袭。
$template = @'
#N Last Name {[string]Last*:last1}
#D First Name: {[string]First:first1}
#P Middle Name: {[string]Middle:A}
#C ID Number: (1) {[int]ID:11111}
#S Status: (1) {[string]Status:status1}
#N Last Name: {[string]Last*:Jane}
#D First Name: {[string]First:Doee}
#P Middle Name: {[string]Middle: s}
#C ID Number: (1) {[int]ID:11111}
#S Status: (1) {[string]Status:Active}
{!Last*:ID Number: (2) 1231
Status: (2) Active}
'@
现在我们将该模板应用于您的数据。首先,我们将解析一个here字符串。
@'
#N Last Name: Joe
#D First Name: Doe
#P Middle Name: A
Some Data:
#C ID Number: (1) 12345
#S Status: (1) Active
#N Last Name: Jane
#D First Name: Doee
#P Middle Name:
Some Data:
#C ID Number: (1) 11111
#S Status: (1) Active
ID Number: (2) 1231
Status: (2) Active
'@ | ConvertFrom-String -TemplateContent $template -OutVariable results
输出
Last : Joe
First : Doe
Middle : A
ID : 12345
Status : Active
Last : Jane
First : Doee
ID : 11111
Status : Active
现在我们可以构造我们的对象,为导出做准备。
$results | foreach {
[pscustomobject]@{
FirstName = $_.first
LastName = $_.last
MidName = $_.middle
IdNumber = $_.id
Status = $_.status
}
} -OutVariable export
现在我们可以出口
$export | Export-Csv -Path .output.csv -NoTypeInformation
这是output.csv 中的内容
PS C:> Get-Content .output.csv
"FirstName","LastName","MidName","IdNumber","Status"
"Doe","Joe","A","12345","Active"
"Doee","Jane",,"11111","Active"
这是从文件中读取的相同内容。
$template = @'
#N Last Name {[string]Last*:last1}
#D First Name: {[string]First:first1}
#P Middle Name: {[string]Middle:A}
#C ID Number: (1) {[int]ID:11111}
#S Status: (1) {[string]Status:status1}
#N Last Name: {[string]Last*:Jane}
#D First Name: {[string]First:Doee}
#P Middle Name: {[string]Middle: s}
#C ID Number: (1) {[int]ID:11111}
#S Status: (1) {[string]Status:Active}
{!Last*:ID Number: (2) 1231
Status: (2) Active}
'@
get-content .ndpcs.txt |
ConvertFrom-String -TemplateContent $template | foreach {
[pscustomobject]@{
FirstName = $_.first
LastName = $_.last
MidName = $_.middle
IdNumber = $_.id
Status = $_.status
}
} | Export-Csv -Path .output.csv -NoTypeInformation
让我们仔细检查一下CSV的内容,以确保万无一失。
Get-Content .output.csv
"FirstName","LastName","MidName","IdNumber","Status"
"Doe","Joe","A","12345","Active"
"Doee","Jane",,"11111","Active"
需要注意的几点:如果之后的数据集具有不同的特征,则需要向模板中添加更多样本。如果不应该有额外的两行(ID和状态(,只需删除模板的这一部分。
我建议每个人在处理逻辑/构建脚本时都使用-outvariable参数,因为您可以同时看到输出并分配给变量。
这是可行的,但它是丑陋的罪恶。
# Get content from text file
$Txtfile = Get-Content "C:temptest.txt" -raw
# Add delimiter to split users
$Delimiter = "
"
$Users = $Txtfile -split $Delimiter
# Create an array list to add data to so it can be exported later.
$collectionVariable = New-Object System.Collections.ArrayList
ForEach($Grouping in $Users) {
$temp = New-Object System.Object
$temp | Add-Member -MemberType NoteProperty -Name "#N" -Value (([regex]::match($Grouping, '#N.*').value) -split " ")[-1]
$temp | Add-Member -MemberType NoteProperty -Name "#D" -Value (([regex]::match($Grouping, '#D.*').value) -split " ")[-1]
$temp | Add-Member -MemberType NoteProperty -Name "#P" -Value (([regex]::match($Grouping, '#P.*').value) -split " ")[-1]
$temp | Add-Member -MemberType NoteProperty -Name "#C" -Value (([regex]::match($Grouping, '#C.*').value) -split " ")[-1]
# This is [-2] due to new line at end of the groupings.
$temp | Add-Member -MemberType NoteProperty -Name "#S" -Value (([regex]::match($Grouping, '#S.*').value) -split " ")[-2]
$collectionVariable.Add($temp) | Out-Null
}