[英]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选项
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 SMO和SQLPSX :
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.