SQL - Execute SQL Script with SQL or Windows Authentication
Octopus.Script exported 09/16/2021 by harrisonmeister belongs to 'SQL Server' category.
Executes SQL script file(s) against the specified database using either SQL or Windows authentication. SQL Scripts can be hardcoded value or can be from an extracted NuGet package.
Parameters
When steps based on the template are included in a project's deployment process, the parameters below can be set.
Server Instance Name
The SQL Server Instance name
Database Name
The database name
Authentication
The authentication method
Username
The username to use to connect (only applies with SqlAuthentication selected)
Password
The password to use to connect (only applies with SqlAuthentication selected)
SQL Scripts
Full path to each script name on a new line Wildcards are accepted, eg. C:\Scripts*.sql, C:\Scripts\Deploy*.sql
DACPAC Package Extract Step Name
Optional: The step in which the DACPAC package was installed. Can be left as blank if SQLScripts is a hardcoded value.
Script body
function Get-DBConnection
{
[CmdletBinding()]
param
(
[Parameter(Position = 0)]
[string]
[ValidateNotNullorEmpty()]
$serverInstance,
[switch]
$SqlAuthentication,
[string]
$Username,
[string]
$Password
)
try
{
$connection = (New-Object Microsoft.SqlServer.Management.Smo.Server($serverInstance))
if ($SqlAuthentication)
{
$connection.ConnectionContext.LoginSecure = $false
$connection.ConnectionContext.set_Login($Username)
$securePassword = ConvertTo-SecureString $Password -AsPlainText -Force
$connection.ConnectionContext.set_SecurePassword($securePassword)
}
$connection.Refresh()
return $connection
}
catch
{
throw $_.Exception.ToString()
}
}
function Invoke-ExecuteSQLScript {
[CmdletBinding()]
param
(
[parameter(Mandatory = $true, Position = 0)]
[ValidateNotNullOrEmpty()]
[string]
$serverInstance,
[parameter(Mandatory = $true, Position = 1)]
[ValidateNotNullOrEmpty()]
[string]
$dbName,
[string]
$Authentication,
[string]
$Username,
[string]
$Password,
[string]
$SQLScripts
)
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | out-null
if ($Authentication -eq "SqlAuthentication")
{
$SqlServer = Get-DBConnection -serverInstance $serverInstance -SqlAuthentication -Username $Username -Password $Password
}
else
{
$SqlServer = Get-DBConnection -serverInstance $serverInstance
}
if ($null -eq $SqlServer.Databases[$dbName])
{
throw "Database $dbName does not exist on server $serverInstance"
}
if ($null -ne $SqlServer)
{
foreach ($SQLScript in $SQLScripts.Split("`n"))
{
try
{
$children = $SQLScript -replace ".*\\"
$replacematch = $children -replace "\*","\*" -replace "\.","\."
$parent = $SQLScript -replace $replacematch
$scripts = Get-ChildItem -Path $parent -Filter $children
foreach ($script in $scripts)
{
$sr = New-Object System.IO.StreamReader($script.FullName)
$scriptContent = $sr.ReadToEnd()
$SqlServer.Databases[$dbName].ExecuteNonQuery($scriptContent)
$sr.Close()
write-verbose ("Executed manual script - {0}" -f $script.Name)
}
}
catch
{
Write-Error $_.Exception
}
}
}
}
if (Test-Path Variable:OctopusParameters)
{
if ($null -ne $DacpacPackageExtractStepName -and $DacpacPackageExtractStepName -ne '')
{
Write-Verbose "Dacpac Package Extract Step Name not empty. Locating scripts located in the Dacpac Extract Step."
$installDirPathKey = 'Octopus.Action[{0}].Output.Package.InstallationDirectoryPath' -f $DacpacPackageExtractStepName
$installDirPath = $OctopusParameters[$installDirPathKey]
$ScriptsToExecute = Join-Path $installDirPath $SqlScripts
}
else
{
Write-Verbose "Locating scripts from the literal entry of Octopus Parameter SQLScripts"
$ScriptsToExecute = $OctopusParameters["SQLScripts"]
}
if ($OctopusParameters["Authentication"] -eq "SqlAuthentication")
{
Write-Verbose "Using Sql Authentication"
Invoke-ExecuteSQLScript -serverInstance $OctopusParameters["serverInstance"] `
-dbName $OctopusParameters["dbName"] `
-Authentication $OctopusParameters["Authentication"] `
-Username $OctopusParameters["Username"] `
-Password $OctopusParameters["Password"] `
-SQLScripts $ScriptsToExecute
}
else
{
Write-Verbose "Using Windows Integrated Authentication"
Invoke-ExecuteSQLScript -serverInstance $OctopusParameters["serverInstance"] `
-dbName $OctopusParameters["dbName"] `
-SQLScripts $ScriptsToExecute
}
}To use this template in Octopus Deploy, copy the JSON below and paste it into the Library → Step templates → Import dialog.
Show JSON{
"Id": "3ec610a8-f75c-43da-8d82-8c9b7b334084",
"Name": "SQL - Execute SQL Script with SQL or Windows Authentication",
"Description": "Executes SQL script file(s) against the specified database using either SQL or Windows authentication. SQL Scripts can be hardcoded value or can be from an extracted NuGet package.",
"Version": 169,
"ExportedAt": "2021-09-16T08:42:00.000+00:00",
"ActionType": "Octopus.Script",
"Author": "harrisonmeister",
"Parameters": [
{
"Id": "0ac8c815-697d-4212-aa73-85e265bd1a7a",
"Name": "serverInstance",
"Label": "Server Instance Name",
"HelpText": "The SQL Server Instance name",
"DefaultValue": null,
"DisplaySettings": {
"Octopus.ControlType": "SingleLineText"
}
},
{
"Id": "63a2671c-cd1e-4bd3-acad-59f656f9a698",
"Name": "dbName",
"Label": "Database Name",
"HelpText": "The database name",
"DefaultValue": null,
"DisplaySettings": {
"Octopus.ControlType": "SingleLineText"
}
},
{
"Id": "bc768cdf-3d5f-4a94-8b08-647056eb3977",
"Name": "Authentication",
"Label": "Authentication",
"HelpText": "The authentication method",
"DefaultValue": null,
"DisplaySettings": {
"Octopus.ControlType": "Select",
"Octopus.SelectOptions": "SqlAuthentication\nWindowsIntegrated"
}
},
{
"Id": "e4d6eca3-5de6-4901-8f94-5253c2aea18d",
"Name": "Username",
"Label": "Username",
"HelpText": "The username to use to connect (only applies with SqlAuthentication selected)",
"DefaultValue": null,
"DisplaySettings": {
"Octopus.ControlType": "SingleLineText"
}
},
{
"Id": "d00b988d-bdf3-4376-aec7-90954e3cb635",
"Name": "Password",
"Label": "Password",
"HelpText": "The password to use to connect (only applies with SqlAuthentication selected)",
"DefaultValue": null,
"DisplaySettings": {
"Octopus.ControlType": "SingleLineText"
}
},
{
"Id": "4de1507a-3824-46b0-bf11-126b953c73da",
"Name": "SQLScripts",
"Label": "SQL Scripts",
"HelpText": "Full path to each script name on a new line\nWildcards are accepted, eg. C:\\Scripts\\*.sql, C:\\Scripts\\Deploy*.sql",
"DefaultValue": null,
"DisplaySettings": {
"Octopus.ControlType": "MultiLineText"
}
},
{
"Id": "0fd3b146-02d1-41fc-9f5c-a830e062b239",
"Name": "DacpacPackageExtractStepName",
"Label": "DACPAC Package Extract Step Name",
"HelpText": "Optional: The step in which the DACPAC package was installed. Can be left as blank if SQLScripts is a hardcoded value.",
"DefaultValue": null,
"DisplaySettings": {
"Octopus.ControlType": "StepName"
}
}
],
"Properties": {
"Octopus.Action.Script.ScriptBody": "function Get-DBConnection\n{\n [CmdletBinding()]\n param\n (\n [Parameter(Position = 0)]\n [string]\n [ValidateNotNullorEmpty()]\n $serverInstance,\n\n [switch]\n $SqlAuthentication,\n\n [string]\n $Username,\n\n [string]\n $Password\n )\n try\n {\n $connection = (New-Object Microsoft.SqlServer.Management.Smo.Server($serverInstance))\n\n if ($SqlAuthentication)\n {\n $connection.ConnectionContext.LoginSecure = $false\n $connection.ConnectionContext.set_Login($Username)\n $securePassword = ConvertTo-SecureString $Password -AsPlainText -Force\n $connection.ConnectionContext.set_SecurePassword($securePassword)\n }\n \n $connection.Refresh()\n \n return $connection\n }\n catch\n {\n throw $_.Exception.ToString()\n }\n \n}\n\nfunction Invoke-ExecuteSQLScript {\n\n [CmdletBinding()]\n param\n (\n [parameter(Mandatory = $true, Position = 0)]\n [ValidateNotNullOrEmpty()]\n [string]\n $serverInstance,\n\n [parameter(Mandatory = $true, Position = 1)]\n [ValidateNotNullOrEmpty()]\n [string]\n $dbName,\n\n [string]\n $Authentication,\n\n [string]\n $Username,\n\n [string]\n $Password,\n\n [string]\n $SQLScripts\n )\n\n [System.Reflection.Assembly]::LoadWithPartialName(\"Microsoft.SqlServer.SMO\") | out-null\n\n if ($Authentication -eq \"SqlAuthentication\")\n {\n $SqlServer = Get-DBConnection -serverInstance $serverInstance -SqlAuthentication -Username $Username -Password $Password\n }\n else\n {\n $SqlServer = Get-DBConnection -serverInstance $serverInstance\n }\n\n if ($null -eq $SqlServer.Databases[$dbName])\n {\n throw \"Database $dbName does not exist on server $serverInstance\"\n }\n \n if ($null -ne $SqlServer)\n {\n foreach ($SQLScript in $SQLScripts.Split(\"`n\"))\n {\n try \n {\n $children = $SQLScript -replace \".*\\\\\"\n $replacematch = $children -replace \"\\*\",\"\\*\" -replace \"\\.\",\"\\.\"\n $parent = $SQLScript -replace $replacematch\n\n $scripts = Get-ChildItem -Path $parent -Filter $children\n\n foreach ($script in $scripts)\n {\n $sr = New-Object System.IO.StreamReader($script.FullName)\n $scriptContent = $sr.ReadToEnd()\n $SqlServer.Databases[$dbName].ExecuteNonQuery($scriptContent)\n $sr.Close()\n\n\t\t\t\t\twrite-verbose (\"Executed manual script - {0}\" -f $script.Name)\n }\n }\n catch \n {\n Write-Error $_.Exception\n }\n }\n }\n}\n\nif (Test-Path Variable:OctopusParameters)\n{\n\tif ($null -ne $DacpacPackageExtractStepName -and $DacpacPackageExtractStepName -ne '')\n {\n Write-Verbose \"Dacpac Package Extract Step Name not empty. Locating scripts located in the Dacpac Extract Step.\"\n $installDirPathKey = 'Octopus.Action[{0}].Output.Package.InstallationDirectoryPath' -f $DacpacPackageExtractStepName\n $installDirPath = $OctopusParameters[$installDirPathKey]\n $ScriptsToExecute = Join-Path $installDirPath $SqlScripts\n }\n else\n { \n Write-Verbose \"Locating scripts from the literal entry of Octopus Parameter SQLScripts\"\n $ScriptsToExecute = $OctopusParameters[\"SQLScripts\"]\n }\n if ($OctopusParameters[\"Authentication\"] -eq \"SqlAuthentication\")\n {\n Write-Verbose \"Using Sql Authentication\"\n Invoke-ExecuteSQLScript -serverInstance $OctopusParameters[\"serverInstance\"] `\n -dbName $OctopusParameters[\"dbName\"] `\n -Authentication $OctopusParameters[\"Authentication\"] `\n -Username $OctopusParameters[\"Username\"] `\n -Password $OctopusParameters[\"Password\"] `\n -SQLScripts $ScriptsToExecute\n }\n else\n {\n Write-Verbose \"Using Windows Integrated Authentication\"\n Invoke-ExecuteSQLScript -serverInstance $OctopusParameters[\"serverInstance\"] `\n -dbName $OctopusParameters[\"dbName\"] `\n -SQLScripts $ScriptsToExecute\n }\n}",
"Octopus.Action.Script.Syntax": "PowerShell",
"Octopus.Action.Script.ScriptSource": "Inline",
"Octopus.Action.RunOnServer": "false"
},
"Category": "SQL Server",
"HistoryUrl": "https://github.com/OctopusDeploy/Library/commits/master/step-templates/sql-execute-script-with-authentication.json",
"Website": "/step-templates/3ec610a8-f75c-43da-8d82-8c9b7b334084",
"Logo": "iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAMAAACahl6sAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAD9QTFRFlZ+r3DAr6p+dy8/V4G9t////5efp9M7NrLS+wCYm8/T1vcPK1tnd10xK+fn6/PLyUU5O+eXk3+Hk7O3u7/DxS2XoPwAADb9JREFUeNrsnYl6nbgOgMEYDHghGN7/Wa8k70B6s3AOZD5o2umcSaf+0S4bUbX/kat6QB6QB+QBeUAekAfkAXlAHpAH5AF5QB6QB+QBeUAekAckXMv4XwBZVCPVnwcZlZSNXRrzp0HGTkqplrY1zfKHQboGMZwoGvVXQUbVy152QaPUu3XrJJCl6Xsp1/SBfbdunQJiZd/3zVqqmfprIEb1iLHRpLF5s279FsQ0iCH3etQ03R8CQYyq74/MwTbN3wGxQFGRRJTaJiVL815z/wXIIiviQEunq2lsNyZhvdfcfw6iCMPavl9H20jkgV8gP1F2NRRJmvEvgIA4gAS0B8xkpexEYWB3F0ijAyOxfwAkcsBvHQk53QWW71HwGm8PIhJHazIS98HYdUqBar1TJD8EYQOABGNe+w0J0dj3iuSHIOMw6PRHOyDpdhggE2XvDmLYAChsDh4MSPI1g92DWkGaosbbey0kARbOyFCaTCYgDemioQWp3D+O9EO4NGNCRpIFMKQzjlG9TyS/iOwoE64jjeaVwICOzjeoGfgue38QshPRMV57lhpVjbNemZTMK7X+gaQRSRgQzaz2JDX9CjRiDvWV+gMgRniSltWMMV0TSo1fcIEjEAKUa7k/CDiomkjaeeAU8JEmoRAOuoLp/hWidTJp9RBiipkF07our9fj/Lpmn51MeM2TnAx5gnp/cRZj6P2aD6BdWoBu1QUeiESwWoCu8a10OBfzHUFaATIxoFssfjIx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DFk7ipnoWhLzJUJqBO1BmiXpYfxVyuGzdNzKUglMgHmWQRfWloSDmkYW6BaZwppryeJenYi8eBfqn50ESZNMFARuUyYhnbV2qbBVuXpjQuczdF+nhVO6j3JIszENO4MCkzmx59C3VbpvuWtrUvHr/+9QZdcMPGyUJu2gtyN4U5erV1wZHlLx7H/NWWaRNAKK3fh2572IaIFkNiMXcACb4LKI5KCih8q+PH7QxVV0v36pHlX99WMLLaBfmi8D2I5ytOlZYY6ZtXv2rhOztWNghlp1gdvpxgr1ApnR9f/qaFb+0hRqFsh6tjMNmJIo+J9uWvI/nm9vQaUfIb3JQG0imXz2fRsHn5C2K+e2DArH1QsNhvGKuUR462OWhsr/Llbyf4yaEaGR2Yu83gsVaftLgMUtqN4b/hFR4/O69lk1iUsVTTG+VFofbbz+YN73776VFAH99dG1Iu7l09Uh1bdCdf/wqlXxyXHRML5sD/GBD/jpfx/fJsvOttu589vnXv2KhAIBgYQQNfNg//hBdyQcio+vCjxxpks1gLApmqj+rjox0/5G1BgteVfbaPhTjR6Okwl/kAFtl/9PcGyWqpPutEYFW1dM5CAARkcneJlDwLlVP+dVDhMNdHW8mP45TzriBZ7k+Xi4W9kbMS0v5JkDdeD8gD8oA8IA/IA/KAPCAPyAPygDwgD8gD8oA8IA/IA/IXr/8JMAAhf0RDrOWy2QAAAABJRU5ErkJggg==",
"$Meta": {
"Type": "ActionTemplate"
}
}Provided under the Apache License version 2.0.