10

I've seen examples of running a SQL command from Azure Powershell e.g.

$connectionString = "Data Source=MyDataSource;Initial Catalog=MyDB;User ID=user1;Password=pass1;Connection Timeout=90"
$connection = New-Object -TypeName System.Data.SqlClient.SqlConnection($connectionString)
$query = "CREATE TABLE...." 
$command = New-Object -TypeName System.Data.SqlClient.SqlCommand($query, $connection)
$connection.Open()
$command.ExecuteNonQuery()
$connection.Close()

Is there a way to replace the $query with a reference to an external file that contains an entire SQL script?

Thanks.

asked Apr 21, 2015 at 14:26

1 Answer 1

18

20 more mins of searching and I found it.

$connectionString = "Data Source=MyDataSource;Initial Catalog=MyDB;User ID=user1;Password=pass1;Connection Timeout=90"
$connection = New-Object -TypeName System.Data.SqlClient.SqlConnection($connectionString)
$query = [IO.File]::ReadAllText("C:\...\TestSQL.sql")
$command = New-Object -TypeName System.Data.SqlClient.SqlCommand($query, $connection)
$connection.Open()
$command.ExecuteNonQuery()
$connection.Close()
answered Apr 21, 2015 at 14:48
Sign up to request clarification or add additional context in comments.

1 Comment

Another option would be to invoke sqlcmd to run the script. An example of iterating through multiple files can be found here: link

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.