Powershell - Outputting .txt data to CSV
I used a different approach,
- splitting the file into sections delimited with the dash line and
- 3 different RegExes using named (capture groups) to grep the properties of each line type.
The first on RegEx101.com - all found properties are stored in an intermediate $Row object and if all RegEx matched gathered in
$Csv
## Q:\Test\2018\07\06\SO_51209341.ps1$FileIn = '.\SO_51209341_data.txt'$TodayCsv = '.\SO_51209341_data.csv'$RE1 = [RegEx]'(?m)(?<Date>\d{2}\/\d{2}\/\d{2}) (?<Time>\d{4}) +(?<Terminal>A\d{3}) +(?<User>C[A-Z0-9]+) +(?<Enquirer>.*)$'$RE2 = [RegEx]'\s+SEARCH REF\s+NAME : (?<Enquiry>.+?) (PAGE|CHAPTER) CODE ='$RE3 = [RegEx]'\s+DATE OF BIRTH : (?<DOB>[0-9 /]+?/\d{4})'$Sections = (Get-Content $FileIn -Raw) -split "={30,}`r?`n" -ne ''$Csv = ForEach($Section in $Sections){ $Row= @{} | Select-Object Date,Time,Terminal,User,Enquirer,Enquiry,DOB $Cnt = 0 If ($Section -match $RE1){++$Cnt $Row.Date = $Matches.Date $Row.Time = $Matches.Time $Row.Terminal = $Matches.Terminal $Row.User = $Matches.User $Row.Enquirer = $Matches.Enquirer.Trim() } If ($Section -match $RE2){++$Cnt $Row.Enquiry = $Matches.Enquiry } If ($Section -match $RE3){++$Cnt $Row.DOB = $Matches.DOB } if ($Cnt -eq 3){$Row}}$csv | Format-Table$csv | Export-Csv $Todaycsv -NoTypeInformation
Sample output revised version
> . Q:\Test\2018\07\06\SO_51209341.ps1Date Time Terminal User Enquirer Enquiry DOB---- ---- -------- ---- -------- ------- ---29/05/17 1227 A999 CA75849 8875849 OCBA NCPS RBC/12/1960 DOE/JOHN / /198829/05/17 1424 A999 CA75849 8875849 OCBA NCPS RBC/60/2111 SMITH/SIMON/PETER / /1967
The problem here is that you need to convert objects to string before exporting.
To make your code working you can slightly modify object creation:
$csv = @()for ($i = 0;$i -lt $Date.Length; $i++) {$obj = New-Object -TypeName PSObject Add-Member -InputObject $obj -MemberType NoteProperty -Name "Date" -Value $Date[$i] Add-Member -InputObject $obj -MemberType NoteProperty -Name "Time" -Value $Time[$i] Add-Member -InputObject $obj -MemberType NoteProperty -Name "Terminal" -value $Terminal[$i] Add-Member -InputObject $obj -MemberType NoteProperty -Name "Enquirer" -value $Enquirer[$i] Add-Member -InputObject $obj -MemberType NoteProperty -Name "Enquiry" -value $Enquiry[$i] Add-Member -InputObject $obj -MemberType NoteProperty -Name "DOB" -value $DOB[$i] $csv += $obj}
Explanation:
The issue here is that you try to make a object of arrays while you should create array of objects. That's why when exporting you got System.Object[]
instead of expected value.
Note: take a look at the code you pasted here and file format. This line:
$TopLine = $XmlDocument | Select-String "A1"
should be
$TopLine = $XmlDocument | Select-String "A999"