Thomas Joseph Thomas Joseph - 1 year ago 101
PowerShell Question

Powershell search till a particular keyword

I'm trying to search and extract the sentences that start with a particular keyword, and which exist between/starts/ends with a keyword. The intention is to extract sentences starting with 'ALTER TABLE', which are either nested between 'GO' keyword or have GO on begin or end block of it. The number of sentences that exist between GO keyword could be arbitrary. Here is my sample file and the code that was written to achieve it.

Content of SampleFile.sql

ALTER TABLE [dbo].[test1]
ADD [country] VARCHAR (30) NULL;
alter procedure
some procedure code
Drop table;
ALTER TABLE [dbo].[test2]
ADD [continent] VARCHAR (30) NULL;

My code

$path = 'D:\Script'
$sampleFile = 'SampleFile.sql'
$search = "ALTER TABLE"
(GC $path\$sampleFile -Delimiter 'GO') -match "^$search*"

Using this code, I'm able to fetch the content only of the first set of ALTER, until the GO. If the caret regex is avoided (^), then all instances of 'ALTER TABLE' is printed (which will also include the sentence 'PROCEDURE ALTER TABLE' until the next GO). Only the sentences starting with 'ALTER TABLE' is required.

Answer Source

You just need the multiline modifier:

(GC $path\$sampleFile -Delimiter 'GO') -match "(?m)^$search*"

that will make ^ match the beginning of a line, not the whole string.

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download