Search code examples
powershellstring-parsing

Tokening String for Format-Table


I'm attempting to do something that ought to be simple in Powershell, but I can't for the life of me figure it out. I have a log file that looks like this:

item1:some text 1:more junk I don't care about.
item2:some text 2:more junk I don't care about.
item3:some text 3:more junk I don't care about.
...

I want to use Powershell to split on the ":", grab the first two items, and then somehow convert the result into something that I can pipe to Format-Table. The end result would be output like this:

Column A           Column B
--------           --------
item1              some text 1
item2              some text 2
item3              some text 3
...

I am by no means, a Powershell expert, so please feel free to clean-up my code. This is what I currently have (I've tried several variations):

Get-Content C:\Temp\test.log | %{
    $data = $_.split(":"); 
    $hashString = 'a = ' + $data[0] + " `n b = " + $data[1]; 
    ConvertFrom-StringData -StringData $hashString
} | ft @{Label="Column A"; Expression={$_.a}},  @{Label="Column B"; Expression={$_.b}} -auto

Thanks in advance.


Solution

  • I would use Import-Csv for that... :)

    Import-Csv -Path your.log -Delimiter : -Header ColumnA, ColumnB
    

    You can use any char as delimiter, including colon.