Untitled

mail@pastecode.io avatar
unknown
powershell
3 years ago
1.2 kB
2
Indexable
$url = 'https://raw.githubusercontent.com/readyroll/generate-sql-merge/master/master.dbo.sp_generate_merge.sql';
$temp = [System.IO.Path]::GetTempPath()
$outputfile = "$temp\sp_generate_merge.sql"
 
Write-Host "Downloading script $outputfile ..."
Invoke-WebRequest -Uri $url -OutFile $outputfile
 
$script = Get-Content $outputfile -Raw
 
# Exec script
$databaseServer = 'localhost'
$server = New-Object Microsoft.SqlServer.Management.Smo.Server($databaseServer)
$server.ConnectionContext.ConnectionString = $connectionString
$sql = [IO.File]::ReadAllText($outputfile)
$batches = $sql -split "GO\r\n"
$VerbosePreference = 'Continue'
 
Write-Host "Batches prepared to be executed: $($batches.Count)"
$server.ConnectionContext.BeginTransaction()
$batches | ForEach-Object {
   try
   {
      $r = $server.ConnectionContext.ExecuteNonQuery($_)
   }
   catch
   {
      $server.ConnectionContext.RollBackTransaction()
      Write-Warning -Message $_
      throw
   }
}
if ($server.ConnectionContext.TransactionDepth -gt 0) {
    $server.ConnectionContext.CommitTransaction()
    Write-Host "Instalattion completed successfully."
}