如何使用PowerShell运行sql脚本?

我想使用powershell运行一个sql脚本但是收到错误“术语'Invoke-sqlcmd'不被识别为cmdlet,函数,脚本文件或可操作程序的名称 . 检查名称的拼写,或者是否包含路径,验证路径是否正确,然后重试 . “

我从一些网站找到了以下片段 . 但这只适用于一个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)

2 years ago

您可以按原样使用代码,只需将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()
}