Quantcast
Channel: PowerShell.com – PowerShell Scripts, Tips, Forums, and Resources
Viewing all articles
Browse latest Browse all 6937

Spliting up a Text document into blocks

$
0
0

Hello

I have worked out a solution to my issue, but wondered if there is a more elegant way of doing it (for example using RegEx) using less code.

I have a single text file which contains the following

-----BEGIN NEW CERTIFICATE REQUEST-----
Trees
Trees
Trees
Flowers
-----END NEW CERTIFICATE REQUEST-----
-----BEGIN NEW CERTIFICATE REQUEST-----
Cats
Cats
Dogs
-----END NEW CERTIFICATE REQUEST-----

Now start and end are markers form a given section so..

-----BEGIN NEW CERTIFICATE REQUEST-----
Trees
Trees
Trees
Flowers
-----END NEW CERTIFICATE REQUEST-----

forms section 1

and

-----BEGIN NEW CERTIFICATE REQUEST-----
Cats
Cats
Dogs
-----END NEW CERTIFICATE REQUEST-----

forms section 2

There my be 1 section or 100, or any number e.g. do not know how many sections the file will contain.

I want to extract the data between each section and have each  extracted (saved) to a variable where I can reference each one individually latter on.

I came up with the following which works

cls
$i,$Array2,$Data=$null
$Data = gc c:\temp\csr.csr

foreach ($line in $Data) {

if ($line -match "BEGIN NEW CERTIFICATE REQUEST") {$Start = 1;$Array1= @()} else {$start = 0}

if ($line -match "END NEW CERTIFICATE REQUEST") {$End = 1;[array]$Array2 += $Array1 | Out-String } else {$End = 0}


 if ((!($Start)) -and (!($End)))  {
 
 [array]$Array1 += $line

 }

}

$Array2

Can anyone show me a better way to do the above please,

Thanks

AAnotherUser__


Viewing all articles
Browse latest Browse all 6937

Trending Articles