Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # https://www.reddit.com/r/PowerShell/comments/4fz7i7/parse_text_into_a_table/
- function ParseTextIntoATable {
- param (
- [string]$InputFile,
- [string[]]$Keys,
- [string]$OutputFile
- )
- if (!$OutputFile) {
- $OutputFile = $InputFile -replace '\.txt$', '.csv'
- }
- $txtFile = Get-Content $InputFile
- $txtFile += 'END'
- $hash = $null
- @(foreach ($line in $txtFile) {
- if ($line.StartsWith('Fname')) {
- if ($hash) {
- [pscustomobject]$hash
- }
- $hash = @{}
- } elseif ($line -eq 'END') {
- [pscustomobject]$hash
- continue
- }
- foreach ($key in $keys) {
- if ($line -match $key) {
- $line = ($line -replace $key).Trim()
- if ('Phone' -in $hash.Keys) {
- $temphash = @{}
- $keep = (diff 'Phone' @($hash.Keys)).inputobject
- foreach ($oldkey in $keep) {
- $temphash.Add($oldkey, $hash[$oldkey])
- }
- [pscustomobject]$hash
- $hash = $temphash
- }
- $hash.Add($key, $line)
- }
- }
- }) | select $keys | Export-Csv $OutputFile -NoTypeInformation
- }
- ParseTextIntoATable -InputFile C:\temp\test.txt -Keys 'Fname', 'Lname', 'Phone'
Advertisement
Add Comment
Please, Sign In to add comment