[英]How to execute .sql file using powershell?
I have a .我有一个 。
sql
file. sql
文件。 I am trying to pass connection string details through a Powershell script and invoke an .sql
file.我正在尝试通过 Powershell 脚本传递连接字符串详细信息并调用
.sql
文件。
I was searching and came up with a cmdlet related to Invoke-sqlcmd
.我正在搜索并想出了一个与
Invoke-sqlcmd
相关的 cmdlet。 While I was trying to find a module corresponding to SQL, I did not find any one in my machine.当我试图找到一个对应于 SQL 的模块时,我没有在我的机器中找到任何一个。
Should I install anything in my machine (the machine already has SQL Server Management Studio 2008 R2) to get the modules or is there any easy way to execute .sql
files using Powershell?我应该在我的机器上安装任何东西(机器已经有 SQL Server Management Studio 2008 R2)来获取模块,还是有什么简单的方法可以使用 Powershell 执行
.sql
文件?
Try to see if SQL snap-ins are present:尝试查看是否存在 SQL 管理单元:
get-pssnapin -Registered
Name : SqlServerCmdletSnapin100
PSVersion : 2.0
Description : This is a PowerShell snap-in that includes various SQL Server cmdlets.
Name : SqlServerProviderSnapin100
PSVersion : 2.0
Description : SQL Server Provider
If so如果是这样
Add-PSSnapin SqlServerCmdletSnapin100 # here lives Invoke-SqlCmd
Add-PSSnapin SqlServerProviderSnapin100
then you can do something like this:然后你可以做这样的事情:
invoke-sqlcmd -inputfile "c:\mysqlfile.sql" -serverinstance "servername\serverinstance" -database "mydatabase" # the parameter -database can be omitted based on what your sql script does.
Quoting from Import the SQLPS Module on MSDN,引用 MSDN 上的Import the SQLPS Module ,
The recommended way to manage SQL Server from PowerShell is to import the sqlps module into a Windows PowerShell 2.0 environment.
从 PowerShell 管理 SQL Server 的推荐方法是将 sqlps 模块导入 Windows PowerShell 2.0 环境。
So, yes, you could use the Add-PSSnapin
approach detailed by Christian, but it is also useful to appreciate the recommended sqlps module approach.所以,是的,您可以使用 Christian 详述的
Add-PSSnapin
方法,但欣赏推荐的 sqlps 模块方法也很有用。
The simplest case assumes you have SQL Server 2012: sqlps is included in the installation so you simply load the module like any other (typically in your profile ) via Import-Module sqlps
.最简单的情况假设您拥有 SQL Server 2012:安装中包含sqlps ,因此您只需通过
Import-Module sqlps
像任何其他模块(通常在您的配置文件中)一样加载模块。 You can check if the module is available on your system with Get-Module -ListAvailable
.您可以使用
Get-Module -ListAvailable
检查系统上的模块是否可用。
If you do not have SQL Server 2012, then all you need do is download the sqlps module into your modules directory so Get-Module/Import-Module will find it.如果您没有 SQL Server 2012,那么您只需将sqlps模块下载到您的模块目录中,以便 Get-Module/Import-Module 找到它。 Curiously, Microsoft does not make this module available for download!
奇怪的是,微软没有提供这个模块供下载! However, Chad Miller has kindly packaged up the requisite pieces and provided this module download .
但是,Chad Miller 已将必要的部分打包并提供此模块下载。 Unzip it under your ...Documents\WindowsPowerShell\Modules directory and proceed with the import.
将其解压缩到您的 ...Documents\WindowsPowerShell\Modules 目录下,然后继续导入。
It is interesting to note that the module approach and the snapin approach are not identical.有趣的是,模块方法和 snapin 方法并不相同。 If you load the snapins then run
Get-PSSnapin
( without the -Registered parameter, to show only what you have loaded) you will see the SQL snapins.如果加载管理单元然后运行
Get-PSSnapin
(不带-Registered 参数,仅显示已加载的内容),您将看到 SQL 管理单元。 If, on the other hand, you load the sqlps module Get-PSSnapin
will not show the snapins loaded, so the various blog entries that test for the Invoke-Sqlcmd
cmdlet by only examining snapins could be giving a false negative result.另一方面,如果您加载 sqlps 模块
Get-PSSnapin
将不会显示加载的管理单元,因此仅通过检查管理单元来测试Invoke-Sqlcmd
cmdlet 的各种博客条目可能会给出假阴性结果。
2012.10.06 Update 2012.10.06 更新
For the complete story on the sqlps module vs. the sqlps mini-shell vs. SQL Server snap-ins, take a look at my two-part mini-series Practical PowerShell for SQL Server Developers and DBAs recently published on Simple-Talk.com where I have, according to one reader's comment, successfully "de-confused" the issue.有关 sqlps 模块与 sqlps mini-shell 与 SQL Server 管理单元的完整故事,请查看我最近在 Simple-Talk.com 上发布的面向 SQL Server 开发人员和 DBA 的两部分迷你系列实用 PowerShell根据一位读者的评论,我成功地“消除了混淆”这个问题。 :-)
:-)
if(Test-Path "C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS") { #Sql Server 2012
Import-Module SqlPs -DisableNameChecking
C: # Switch back from SqlServer
} else { #Sql Server 2008
Add-PSSnapin SqlServerCmdletSnapin100 # here live Invoke-SqlCmd
}
Invoke-Sqlcmd -InputFile "MySqlScript.sql" -ServerInstance "Database name" -ErrorAction 'Stop' -Verbose -QueryTimeout 1800 # 30min
Here is a function that I have in my PowerShell profile for loading SQL snapins:这是我的 PowerShell 配置文件中用于加载 SQL 管理单元的函数:
function Load-SQL-Server-Snap-Ins
{
try
{
$sqlpsreg="HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.SqlServer.Management.PowerShell.sqlps"
if (!(Test-Path $sqlpsreg -ErrorAction "SilentlyContinue"))
{
throw "SQL Server Powershell is not installed yet (part of SQLServer installation)."
}
$item = Get-ItemProperty $sqlpsreg
$sqlpsPath = [System.IO.Path]::GetDirectoryName($item.Path)
$assemblyList = @(
"Microsoft.SqlServer.Smo",
"Microsoft.SqlServer.SmoExtended",
"Microsoft.SqlServer.Dmf",
"Microsoft.SqlServer.WmiEnum",
"Microsoft.SqlServer.SqlWmiManagement",
"Microsoft.SqlServer.ConnectionInfo ",
"Microsoft.SqlServer.Management.RegisteredServers",
"Microsoft.SqlServer.Management.Sdk.Sfc",
"Microsoft.SqlServer.SqlEnum",
"Microsoft.SqlServer.RegSvrEnum",
"Microsoft.SqlServer.ServiceBrokerEnum",
"Microsoft.SqlServer.ConnectionInfoExtended",
"Microsoft.SqlServer.Management.Collector",
"Microsoft.SqlServer.Management.CollectorEnum"
)
foreach ($assembly in $assemblyList)
{
$assembly = [System.Reflection.Assembly]::LoadWithPartialName($assembly)
if ($assembly -eq $null)
{ Write-Host "`t`t($MyInvocation.InvocationName): Could not load $assembly" }
}
Set-Variable -scope Global -name SqlServerMaximumChildItems -Value 0
Set-Variable -scope Global -name SqlServerConnectionTimeout -Value 30
Set-Variable -scope Global -name SqlServerIncludeSystemObjects -Value $false
Set-Variable -scope Global -name SqlServerMaximumTabCompletion -Value 1000
Push-Location
if ((Get-PSSnapin -Name SqlServerProviderSnapin100 -ErrorAction SilentlyContinue) -eq $null)
{
cd $sqlpsPath
Add-PsSnapin SqlServerProviderSnapin100 -ErrorAction Stop
Add-PsSnapin SqlServerCmdletSnapin100 -ErrorAction Stop
Update-TypeData -PrependPath SQLProvider.Types.ps1xml
Update-FormatData -PrependPath SQLProvider.Format.ps1xml
}
}
catch
{
Write-Host "`t`t$($MyInvocation.InvocationName): $_"
}
finally
{
Pop-Location
}
}
Here's a light weight approach for simple scripts that requires no additional tools / setup / PowerShell add-ons.这是一种无需额外工具/设置/PowerShell 附加组件的简单脚本的轻量级方法。
$conn = New-Object System.Data.SqlClient.SqlConnection
$conn.ConnectionString = $connectionStringGoesHere
$conn.Open()
$content = Get-Content $scriptFileNameGoesHere
$cmds = New-Object System.Collections.ArrayList
$cmd = ""
$content | foreach {
if ($_.Trim() -eq "GO") { $cmds.Add($cmd); $cmd = "" }
else { $cmd = $cmd + $_ +"`r`n" }
}
$cmds | foreach {
$sc = New-Object System.Data.SqlClient.SqlCommand
$sc.CommandText = $_
$sc.Connection = $conn
$sc.ExecuteNonQuery()
}
with 2008 Server 2008 and 2008 R2使用 2008 Server 2008 和 2008 R2
Add-PSSnapin -Name SqlServerCmdletSnapin100, SqlServerProviderSnapin100
with 2012 and 2014 2012 年和 2014 年
Push-Location
Import-Module -Name SQLPS -DisableNameChecking
Pop-Location
Invoke-Sqlcmd -Database MyDatabase -Query "exec dbo.sp_executesql N'$(Get-Content "c:\my.sql")'"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.