Question : Execute SQL Script using PowerShell

I am trying to execute the PowerShell script (shown in code), but the script only runs the first line on the SQL script ("C:\script1.sql"). How can I can this to run the entire SQL script?

Here is the text of "C:\script1.sql"

use master;

create database (test);

use test;

create table mytest (
      myid int
);

insert into mytest values(1);

Here is the text of "C:\serv.txt":

MyServer
MyServer2
Code Snippet:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
$cmd = get-content "C:\script1.sql"
 
foreach ($svr in get-content "C:\serv.txt")
{
  $con = "server=$svr;database=master;Integrated Security=sspi"
  $da = new-object System.Data.SqlClient.SqlDataAdapter ($cmd, $con)
  $dt = new-object System.Data.DataTable
  $da.fill($dt) | out-null
  $svr
  $dt | format-table
}
Open in New Window Select All

Answer : Execute SQL Script using PowerShell

try the folloing function
just define $sqlquery to be one or more lines of SQL code, and dont use go
Good luck
joe
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 Function GetSqlDAtaSet 
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# usage:  #
#-=-=-=-=-= 
# $myinfo   = Getsqldataset $sqlquery "servername\instance,port" database_name
# $myinfo   = Getsqldataset $sqlquery "server1\test" database1
#
 
{
 Param($sql, 
$server=".",
$SQLdb)
  $sqlConnection                              = new-object System.Data.SqlClient.SqlConnection "Server = $server;Database=$SQLdb;Integrated Security=True"
  $return_value                                 = $sqlConnection.Open()
  $sqlCommand                                                 = New-object system.data.sqlclient.SqlCommand   
  $sqlCommand.CommandTimeout         = 30 
  $sqlCommand.Connection        = $sqlConnection
  $sqlCommand.CommandText                 =  $sql
  $sqlDataAdapter                            = new-object System.Data.SqlClient.SQLDataAdapter($sqlCommand) 
  $sqlDataSet                                      = new-object System.Data.dataset 
  $sqlDataAdapter.fill($sqlDataSet)                                                         # move data into dataset
 
                $mydata              = $sqlDataSet.tables[0].select()
                $sqlconnection.close() # close connection
                return $mydata                                # return object 
}
Open in New Window Select All
Random Solutions  
 
programming4us programming4us