简体   繁体   English

从Powershell运行SQL Server命令?

[英]Running SQL Server commands from Powershell?

I'm writing a Powershell script to automate something with SQL Server, and part of that requires adding my local account to the database as an admin. 我正在编写Powershell脚本来使用SQL Server自动化某些操作,其中一部分需要以管理员身份将本地帐户添加到数据库中。

create login [MYDOMAIN\myusername] from windows
go

sp_addsrvrolemember [MYDOMAIN\myusername], 'sysadmin'
go

This needs to be run through an elevated sqlcmd command. 这需要通过提升的sqlcmd命令运行。

I'm new to both Powershell and SQL Server, so thank you for your help. 我是Powershell和SQL Server的新手,所以谢谢您的帮助。

You are looking for Invoke-Sqlcmd cmdlet . 您正在寻找Invoke-Sqlcmd cmdlet

Save your SQL Server command (below ones) in a file and save it as SQLInput.sql 将SQL Server命令(以下命令)保存在文件中,并将其另存为SQLInput.sql

create login [MYDOMAIN\myusername] from windows
go

sp_addsrvrolemember [MYDOMAIN\myusername], 'sysadmin'
go

Then, You can run PowerShell command prompt with Run As Administrator and run the below command like: 然后,您可以使用Run As Administrator身份Run As Administrator来运行PowerShell命令提示符,并运行以下命令,如下所示:

Invoke-Sqlcmd -InputFile "C:\SQLInput.sql" | Out-File -filePath "C:\SQLOutput.rpt"

EDIT: 编辑:

You can use -Query option to run the query inline like 您可以使用-Query选项以类似方式内联运行查询

Invoke-Sqlcmd -Query "create login [MYDOMAIN\myusername] from windows;"

Catching response, is to make sure whether Query ran successfully or not. 捕获响应是为了确保查询是否成功运行。 You can use -AbortOnError switch; 您可以使用-AbortOnError开关; which will abort the command on error. 错误时中止命令。

Else, you can use Try .. Catch .. Finally construct in PowerShell like 否则,您可以使用Try .. Catch .. Finally在PowerShell中像

Try
 {
   Invoke-Sqlcmd -Query "create login [MYDOMAIN\myusername] from windows;"
 }

Catch
 {
  [system.exception]
  "caught a system exception"
 }

Finally
 {
  "end of script"
 }

Read more about exception handling in Powershell Here 此处阅读有关Powershell中异常处理的更多信息

There are a few popular TSQL options from PowerShell PowerShell提供了一些流行的TSQL选项

  • Invoke-SqlCmd2 调用SqlCmd2
    • Download and dot source the function 下载点源功能
    • + Flexible, portable TQSL function based on .NET in ~400 lines +约400行中基于.NET的灵活,便携式TQSL功能
    • + Simple parameterized queries +简单的参数化查询
    • + Optional efficient conversion of DBNull to Null (data bahaves as expected in PowerShell) +可选的DBNull到Null的有效转换(PowerShell中预期的数据行为)
    • - Not an official Cmdlet from Microsoft -不是Microsoft的官方Cmdlet
    • - Does not support 'Go' statement -不支持'Go'语句


  • Invoke-SqlCmd 调用SqlCmd
    • Download and install the latest SQL Feature pack (generally backwards compatible). 下载并安装最新的SQL Feature Pack (通常向后兼容)。 In particular: 尤其是:
      • SQLSysClrTypes SQLSysClrTypes
      • Shared ManagementObjects 共享管理对象
      • PowerShellTools PowerShell工具
    • Alternatively, install Management Tools along with SQL 或者,将管理工具与SQL一起安装
    • + Official Cmdlet from Microsoft +微软官方Cmdlet
    • - No support for parameterized queries (or terrible wonky - is 'Variable' parameter for this?) -不支持参数化查询(或糟糕透顶-为此使用“变量”参数吗?)
    • - Known to be buggy. -已知是越野车。 As of SQL 2014 CTP there were still bugs being addressed 自SQL 2014 CTP起, 仍然存在一些错误已得到解决


  • .NET - System.Data.SqlClient .NET-System.Data.SqlClient
    • Search MSDN for various classes. 在MSDN中搜索各种类。 Examples abound on this site. 这个网站上有很多例子。
      • System.Data.SqlClient.SQLConnection System.Data.SqlClient.SQLConnection
      • System.Data.SqlClient.SqlCommand System.Data.SqlClient.SqlCommand
      • System.Data.DataSet System.Data.DataSet
      • System.Data.SqlClient.SqlDataAdapter System.Data.SqlClient.SqlDataAdapter
    • + Portable +便携式
    • + Powerful +强大
    • - Not as simple as a Cmdlet or function -不像Cmdlet或函数那么简单
    • - Readers may find your code less clear -读者可能会发现您的代码不太清楚
    • - While helpful if you have specific niche needs, re-usable code like Invoke-SqlCmd2 would be more efficient -如果您有特定的利基需求会有所帮助,但可重复使用的代码(例如Invoke-SqlCmd2)会更有效


  • sqlcmd.exe sqlcmd.exe
    • If you really want to call it, you can call it from PowerShell. 如果您确实要调用它,则可以从PowerShell中调用它。 You might find --% helpful... 您可能会发现-%的帮助...


Example use with Invoke-SqlCmd2 (generally my go command for TSQL): 与Invoke-SqlCmd2一起使用的示例(通常是TSQL的go命令):

Invoke-Sqlcmd2 -ServerInstance SomeInstance -Database SomeDatabase -Query "create login [MYDOMAIN\myusername] from windows;"


On a side note, be sure to check out the SQL SMO , and SQLPSX : 附带说明一下,请确保签出SQL SMOSQLPSX

  • The SQL SMO is fantastic for automation and control of SQL, although you would need to be comfortable with using .NET. SQL SMO非常适合用于SQL的自动化和控制,尽管您需要习惯使用.NET。 There are many resources available, just google around for what you want to do, and tack on 'SQL SMO PowerShell' 很多可用资源,只需谷歌搜索您想做什么,然后使用“ SQL SMO PowerShell”
  • SQLPSX generally uses .NET and the SMO libraries, providing more user friendly functions that behave like Cmdlets. SQLPSX通常使用.NET和SMO库,提供行为类似于Cmdlet的更加用户友好的功能。 Unfortunately, this appears to be a dead project, and some of the material is dated. 不幸的是,这似乎是一个无效的项目,并且其中一些材料已过时。 Here's a good post on getting started by one of the contributors. 这是其中一位贡献者入门的好帖子

    Good luck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM