Here is yet another recommendation. What I'm suggesting is to use ConvertFrom-String.
First we'll make a template, I accounted for the junk two lines in your sample data. I'm really hoping that's a typo/copyo.
$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}
'@
Now we apply that template to your data. First we will parse a here-string.
@'
#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
Output
Last : Joe
First : Doe
Middle : A
ID : 12345
Status : Active
Last : Jane
First : Doee
ID : 11111
Status : Active
Now we can construct our object in preparation to export.
$results | foreach {
[pscustomobject]@{
FirstName = $_.first
LastName = $_.last
MidName = $_.middle
IdNumber = $_.id
Status = $_.status
}
} -OutVariable export
And now we can export it
$export | Export-Csv -Path .\output.csv -NoTypeInformation
Here is what's in output.csv
PS C:\> Get-Content .\output.csv
"FirstName","LastName","MidName","IdNumber","Status"
"Doe","Joe","A","12345","Active"
"Doee","Jane",,"11111","Active"
Here's the same thing reading it from a file instead.
$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
Let's double check the contents of our CSV just to be sure.
Get-Content .\output.csv
"FirstName","LastName","MidName","IdNumber","Status"
"Doe","Joe","A","12345","Active"
"Doee","Jane",,"11111","Active"
A couple things to note:
If the datasets after this have different characteristics, you'll need to add more samples to the template.
If the two extra lines (ID and status) shouldn't be there, simply remove that part of the template.
I recommend everyone use the -outvariable parameter when working out logic/building scripts as you can see the output and assign to a variable at the same time.