user2714683
user2714683

Reputation: 1

Powershell - Splitting multiple lines of text into individual records

Fairly new to PowerShell and wondering if someone could provide a hand with the following. Basically I have a .txt document with a number of records separated by a special character ($)(e.g)

ID
Date Entered
Name
Title
Address
Phone
$
ID
Date Entered
Name
Title
Address
Phone
$

I want to split each item between the $ into individual "records" so that I can loop through each record. So for example I could check each record above and return the record ID for all records that didn't have a phone number entered.

Thanks in advance

Upvotes: 0

Views: 2151

Answers (2)

Baldwin D.
Baldwin D.

Reputation: 110

I once had the same requirement... this is how I did it

$loglocation = "C:\test\dump.txt"
$reportlocation = "C:\test\dump.csv"
$linedelimiter = ":"
$blockdelimiter = "FileSize"

$file = Get-Content $loglocation

$report = @()
$block = @{}

foreach ($line in $file)
{ 

    if($line.contains($linedelimiter))
        {
        $key = $line.substring(0,$line.indexof($linedelimiter)).trimend()
        $value = $line.substring($line.indexof($linedelimiter)+1).trimstart()

        $block.Add($key,$value)

        if ($block.keys -contains $blockdelimiter)
            {
            $obj = new-object psobject -property $block
            $report += $obj
            $block = @{}
            }
        }
}

$report
$report | Export-Csv $reportlocation -NoTypeInformation

So you cycle through each line, define key and value and add the object to a hashtable. Once the keys contains the blockdelimiter a new object gets written to an array and the hashtable gets cleared.

In my case the linedelimiter was a colon and the blockdelimiter was a valid record so you will have to make some changes. Let me know if this approach suits your needs and you can't find what to do.

P.S. By default only the noteproperties of the first object in the array will be shown so you will have to pipe the array to Select-Object and add all properties needed.

Grts.

Upvotes: 1

Andy Arismendi
Andy Arismendi

Reputation: 52567

If each record contains a fixed number of properties you can take this approach. It loops through creating custom objects while skipping the dollar sign line.

$d = Get-Content -Path C:\path\to\text\file.txt
for ($i = 0; $i -lt $d.Length; $i+=7) {
    New-Object -TypeName PsObject -Property @{
        'ID'           = $d[$i]
        'Date Entered' = $d[$i+1]
        'Name'         = $d[$i+2]
        'Title'        = $d[$i+3]
        'Address'      = $d[$i+4]
        'Phone'        = $d[$i+5]
    }
}

Upvotes: 1

Related Questions