在powershell脚本中执行sql命令

时间:2017-04-21 06:49:24

标签: sql-server windows powershell

我想通过直接输入来执行我在命令上执行的简单sql命令,但我想使用Powershell脚本执行此操作,不想使用powershell API执行命令,只需调用命令

sqlcmd -S .\SQLEXPRESS -U SA -P mypass
USE [master]
RESTORE DATABASE [easypay] FROM  DISK = N'C:\backup.trn' WITH  FILE = 1,  NOUNLOAD,  REPLACE,  STATS = 5
ALTER LOGIN [itdb] WITH PASSWORD=N'abc'
GO
USE [easypay]
GO
EXEC sp_change_users_login 'Auto_Fix', 'itdb'
Go
USE [easypay]
GO
sp_changedbowner 'sa'
GO

UPDATE itdb.passwd set password = '1a1dc91c907325c69271ddf0c944bc72'  WHERE itdb.passwd.name = 'abc'
GO

我想要一个可以执行这些命令direclty的powershell脚本 感谢

1 个答案:

答案 0 :(得分:0)

这是我使用的一个脚本,稍加修改。 请注意,此代码未经测试:

在Kirill Pashkov的评论之后做了一些改变

$SQLServer = "" #your value
$SQLDBName = "" #your value

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
#Start SQL connection
$SqlCmd.Connection = $SqlConnection

#Create querys
#Query 1
$SqlQuery = "Command;"

#Query 2
$SqlQuery2 = @"
 Command
"@

#Add querys to array
$querys = $SqlQuery, $SqlQuery2

# Run Query
Foreach($query in $querys)
{
    $SqlCmd.CommandText = $query
    $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
    $SqlAdapter.SelectCommand = $SqlCmd
    $DataSet = New-Object System.Data.DataSet
    $OutPut = $SqlAdapter.Fill($DataSet)
    if($OutPut -ne 0){
    Write-Host $OutPut
    }

}
#Close SQL connection
$SqlConnection.Close()