Search code examples
powershellpowershell-3.0powershell-4.0

Remove redundant GOs from SQL script using Powershell


I need to remove redundant GO statements from a large SQL file before it gets passed through Invoke-sqlcmd for deployment. Multiple GO statements together causes "There are no batches in the input script" and using -OutputSqlErrors $false masks all other errors.

Get-Unique deletes all duplicate data - which is not desirable. I would only like to delete the duplicate GO statements

Current Script:

Exec (@SQLScript)
Print @SQLScript
End
GO
GO

if obj is not null
    drop procedure 
go

CREATE PROC 
    @al varchar(16),
    @rule      varchar(128)
END CATCH
GO
GO

If Exists (Select * From Table)
Go 
    Set @Start = DateAdd(m, 1, @Start)
End 
GO
GO

I would like to get a script like this:

Exec (@SQLScript)
Print @SQLScript
End
GO

if obj is not null
    drop procedure 
go

CREATE PROC 
    @al varchar(16),
    @rule      varchar(128)
END CATCH
GO

If Exists (Select * From Table)
Go 
    Set @Start = DateAdd(m, 1, @Start)
End 
GO

Solution

  • If you load the script into a variable, you can use regular expressions to match and replace multiple "GO" statements. For ex:

    $ReplacedText = $OriginalScript -replace '(GO(\n)*){2,}',"GO`n"
    

    The Regular expression matches "GO" that may or may not be followed by a new line, 2 or more times. and replace it with a single "GO" followed by a new line.