Forum Discussion
how to execute sql script via powershell in azure pipelines yml
Hi amitaiemd,
To authenticate with Windows credentials and execute the SQL script using the runas command in PowerShell, you can use this:
- task: PowerShell@2
displayName: 'Execute SQL Script'
inputs:
targetType: 'inline'
script: |
$serverName = 'your_server_name'
$databaseName = 'your_database_name'
$userName = 'your_username'
$sqlScriptPath = 'path_to_your_sql_script'
# Construct the "runas" command
$runAsCommand = '%windir%\system32\runas.exe'
$runAsArgs = "/netonly /user:domain\username `"sqlcmd.exe -S $serverName -d $databaseName -U $userName -i `"$sqlScriptPath`"`""
# Execute the "runas" command
$processInfo = New-Object System.Diagnostics.ProcessStartInfo
$processInfo.FileName = $runAsCommand
$processInfo.Arguments = $runAsArgs
$processInfo.UseShellExecute = $false
$processInfo.RedirectStandardInput = $true
$processInfo.RedirectStandardOutput = $true
$processInfo.RedirectStandardError = $true
$process = New-Object System.Diagnostics.Process
$process.StartInfo = $processInfo
$process.Start() | Out-Null
$process.WaitForExit()
# Check the exit code
$exitCode = $process.ExitCode
if ($exitCode -eq 0) {
Write-Host "SQL script executed successfully."
} else {
$errorMessage = $process.StandardError.ReadToEnd()
Write-Host "An error occurred while executing the SQL script: $errorMessage"
throw "SQL script execution failed with exit code $exitCode"
}
Please make sure to replace domain\username with your actual domain and username.
Please click Mark as Best Response & Like if my post helped you to solve your issue. This will help others to find the correct solution easily. It also closes the item. If the post was useful in other ways, please consider giving it Like.
Kindest regards
Leon Pavesic
Hi LeonPavesic
I could not see any place for setting the password for the SQL server connection. Which basically when I launch it in my local it prompt me for password. But how to set the password from pipeline side.
Thanks