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.
create login [MYDOMAIN\myusername] from windows
go
sp_addsrvrolemember [MYDOMAIN\myusername], 'sysadmin'
go
This needs to be run through an elevated sqlcmd
command.
I'm new to both Powershell and SQL Server, so thank you for your help.
You are looking for Invoke-Sqlcmd cmdlet
.
Save your SQL Server command (below ones) in a file and save it as 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:
Invoke-Sqlcmd -InputFile "C:\SQLInput.sql" | Out-File -filePath "C:\SQLOutput.rpt"
EDIT:
You can use -Query
option to run the query inline like
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; which will abort the command on error.
Else, you can use Try .. Catch .. Finally
construct in PowerShell like
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
There are a few popular TSQL options from PowerShell
Example use with Invoke-SqlCmd2 (generally my go command for TSQL):
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 :
SQLPSX generally uses .NET and the SMO libraries, providing more user friendly functions that behave like Cmdlets. 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!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.