如何使用PowerShell运行sql脚本?

时间:2014-08-18 10:18:24

标签: sql-server sql-server-2008 powershell powershell-v2.0 powershell-v3.0

我想使用powershell运行一个sql脚本,但是出现错误"术语' Invoke-sqlcmd'不被识别为cmdlet,函数,脚本文件或可操作程序的名称。检查t 他拼写名称,或者如果包含路径,请验证路径是否正确并重试。"

我在某个网站上找到了以下代码段。但这只适用于一个sql命令。但我想运行一个sql脚本。

有人可以帮忙修改下面的sql脚本或更好的建议吗?

   SQLServer = "ABCD\ABC" 
    $SQLDBName = "ABC_1223"
    $SqlQuery = "select * from table" 

    $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
    $SqlConnection.ConnectionString = "Server = $SQLServer; Database  =$SQLDBName;uid=$SQLDBName;pwd= $pwd; Integrated Security = True" 

    $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
    $SqlCmd.CommandText = $SqlQuery
    $SqlCmd.Connection = $SqlConnection 
    $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
    $SqlAdapter.SelectCommand = $SqlCmd 
    $DataSet = New-Object System.Data.DataSet
    $SqlAdapter.Fill($DataSet) 
    $SqlConnection.Close()
    clear 
    $DataSet.Tables[0]

1 个答案:

答案 0 :(得分:4)

您可以按原样使用代码,只需将SQL脚本放在Here-String(字符串文字)中。此外,我将在Try / Catch / Finally构造中包装对SQL数据库的调用,以确保关闭和处理您的连接。最后,考虑在连接字符串中使用Application Name,为DBA提供关于连接相关内容的线索。将它们放在一起:

Try{

  $SQLServer = "ABCD\ABC" 
  $SQLDBName = "ABC_1223"

#This is the here-string
  $SqlQuery = @"
    select * from table
    where we can select stuff
    and filter it
    and join
    etc
"@

  $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
  $SqlConnection.ConnectionString = "Server = $SQLServer; Database  =$SQLDBName;Application Name = 'user2075017_db_call';uid=$SQLDBName;pwd= $pwd; Integrated Security = True" 

  $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
  $SqlCmd.CommandText = $SqlQuery
  $SqlCmd.Connection = $SqlConnection 
  $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
  $SqlAdapter.SelectCommand = $SqlCmd 
  $DataSet = New-Object System.Data.DataSet
  $SqlAdapter.Fill($DataSet) 
  $DataSet.Tables[0]
}
Catch{
}
Finally{
  $SqlConnection.Close()
  $SqlConnection.Dispose()
}