How to create objects from a flat text file.
Last active
September 14, 2016 08:17
-
-
Save XPlantefeve/9e626bf9ec1a89ef354fe13767a96b02 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Topic: NBA All Stars | |
| Owners: Foo Owners | |
| Users: User 1 | |
| Users: User 2 | |
| Topic: NFL MVPs | |
| Owners: Bar Owners | |
| Users: Tony Stark | |
| Users: Mitch Hedberg | |
| Users: Someone Else | |
| Topic: NBA MVPs | |
| Owners: MVP Owners | |
| Users: Jane Smith | |
| Users: John Doe |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # see https://www.reddit.com/r/PowerShell/comments/51mhe8/flat_text_file_to_csv/ | |
| $flatfile = Get-Content -Path .\flatfile.txt | |
| # this will contain every record | |
| $allrecords = @() | |
| # this will contain the property of the current record. | |
| $record = $null | |
| foreach ( $line in $flatfile ) { | |
| Switch -Regex ($line) { | |
| 'Topic: (?<topic>.*)' { | |
| if ( $record ) { | |
| # if there's a previous $record, we | |
| # create the object from it | |
| $record.users = $record.users -join ', ' | |
| $allrecords += New-Object -TypeName psobject -Property $record | |
| } | |
| $record = @{topic=$Matches.topic} | |
| } | |
| 'Owners: (?<owners>.*)' { $record.owners = $Matches.owners } | |
| 'Users: (?<user>.*)' { $record.users += ,$Matches.user } | |
| } | |
| } | |
| # We still have one record in memory | |
| # we add it to the list. | |
| $record.users = $record.users -join ', ' | |
| $allrecords += New-Object -TypeName psobject -Property $record | |
| # print to screen | |
| $allrecords | select topic,owners,users | |
| # export to CSV file | |
| $allrecords | select topic,owners,users | Export-Csv -Path ".\flatfile.csv" -NoTypeInformation |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment