0

I want to remove nonclustered indexes from a script using PowerShell possibly Regex. Background: We have lot of data in database, and want to prevent 1 hr of index creation time, from creating or altering the nonclustered indexes. How to conduct this with PowerShell? PowerShell will take input script and edit accordingly.

Publish Profile Script:

Create table dbo.Test(TestId int, ColumnA int, ColumnB int)

GO
CREATE NONCLUSTERED INDEX [ncx_Test_ColumnA]
    ON [dbo].[Test]([ColumnA] ASC);


GO
PRINT N'Creating [ncx_Test_ColumnA]...';


GO
CREATE NONCLUSTERED INDEX [ncx_Test_ColumnB]
    ON [dbo].[Test]([ColumnB] ASC);


GO
PRINT N'Creating [ncx_Test_ColumnB]...';


GO
create procedure dbo.TestSelect1
as select 1

In the above script, I want to remove the 'Create Nonclustered Index Lines, (and added bonus, not required) would be remove the corresponding Print statements, keep everything else, tables and stored procedures.

Remove these lines only, keep everything else:

CREATE NONCLUSTERED INDEX [ncx_Test_ColumnA]
    ON [dbo].[Test]([ColumnA] ASC);


PRINT N'Creating [ncx_Test_ColumnA]...';


CREATE NONCLUSTERED INDEX [ncx_Test_ColumnB]
    ON [dbo].[Test]([ColumnB] ASC);


PRINT N'Creating [ncx_Test_ColumnB]...';

Good resource for powershell: trying to figure out

Automatically Create Indexes in Different Filegroup, edit Publish Profile Script

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • What have you tried so far? You're more likely to get help if you show some effort. – boxdog May 14 '19 at 21:25
  • Why aren’t your indexes in your database the same as the indexes in your project? – Ed Elliott May 14 '19 at 21:35
  • sorry what I am trying to get at is why you have different indexes in your project to the database? You can avoid the index create/alter time if you have the same indexes in both? – Ed Elliott May 15 '19 at 08:21
  • we don't have different databases, all trying to do is remove a line –  May 15 '19 at 17:49

1 Answers1

0

Can someone code review this? Seems to be working,

$sql = Get-Content C:\Users\TestUser\Desktop\indextext\original.txt -Raw
$sql = $sql -replace '(?smi)(CREATE NONCLUSTERED INDEX (.*?))\);',''
$sql | Set-Content -Path C:\Users\TestUser\Desktop\indextext\new.txt