gangstanthony

ParseTextIntoATable

Apr 22nd, 2016
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # https://www.reddit.com/r/PowerShell/comments/4fz7i7/parse_text_into_a_table/
  2.  
  3. function ParseTextIntoATable {
  4.     param (
  5.         [string]$InputFile,
  6.         [string[]]$Keys,
  7.         [string]$OutputFile
  8.     )
  9.  
  10.     if (!$OutputFile) {
  11.         $OutputFile = $InputFile -replace '\.txt$', '.csv'
  12.     }
  13.  
  14.     $txtFile = Get-Content $InputFile
  15.     $txtFile += 'END'
  16.  
  17.     $hash = $null
  18.     @(foreach ($line in $txtFile) {
  19.         if ($line.StartsWith('Fname')) {
  20.             if ($hash) {
  21.                 [pscustomobject]$hash
  22.             }
  23.             $hash = @{}
  24.         } elseif ($line -eq 'END') {
  25.             [pscustomobject]$hash
  26.             continue
  27.         }
  28.  
  29.         foreach ($key in $keys) {
  30.             if ($line -match $key) {
  31.                 $line = ($line -replace $key).Trim()
  32.                 if ('Phone' -in $hash.Keys) {
  33.                     $temphash = @{}
  34.                     $keep = (diff 'Phone' @($hash.Keys)).inputobject
  35.                     foreach ($oldkey in $keep) {
  36.                         $temphash.Add($oldkey, $hash[$oldkey])
  37.                     }
  38.                     [pscustomobject]$hash
  39.                     $hash = $temphash
  40.                 }
  41.                 $hash.Add($key, $line)
  42.             }
  43.         }
  44.     }) | select $keys | Export-Csv $OutputFile -NoTypeInformation
  45. }
  46.  
  47. ParseTextIntoATable -InputFile C:\temp\test.txt -Keys 'Fname', 'Lname', 'Phone'
Advertisement
Add Comment
Please, Sign In to add comment