本节书摘来自异步社区出版社《PowerShell V3—SQL Server 2012数据库自动化运维权威指南》一书中的第2章,第2.17节,作者:【加拿大】Donabel Santos,更多章节内容可以访问云栖社区“异步社区”公众号查看。
本方案描述了如何用PowerShell执行手写的查询语句或SQL脚本。
在C:Temp目录下创建一个文件SampleScript.sql。它包含:
SELECT * FROM Person.Person1.通过“Start | Accessories | Windows PowerShell | Windows PowerShell ISE”打开PowerShell控制台。
2.导入SQLPS模块,创建一个新的SMO服务器对象。
#import SQL Server module Import-Module SQLPS –DisableNameChecking #replace this with your instance name $instanceName = "KERRIGAN" $server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $instanceName3.添加如下脚本并运行。
$dbName = "AdventureWorks2008R2" $db = $server.Databases[$dbName] #execute a passthrough query, and export to a CSV file Invoke-Sqlcmd ` -Query "SELECT * FROM Person.Person" ` -ServerInstance "$instanceName" ` -Database $dbName | Export-Csv -LiteralPath "C:\Temp\ResultsFromPassThrough.csv" ` -NoTypeInformation #execute the SampleScript.sql, and display results to screen Invoke-SqlCmd ` -InputFile "C:\Temp\SampleScript.sql" ` -ServerInstance "$instanceName" ` -Database $dbName | Select FirstName, LastName, ModifiedDate | Format-Table开始学习Invoke-Sqlcmd cmdlet。我们将会在本书中大量使用。
你可以使用这个cmdlet运行T-SQL代码或脚本,以及被SQLCMD工具集支持的命令,你也可以运行XQuery代码。Invoke-Sqlcmd是你的全能SQL工具集cmdlet。
获得更多关于Invoke-Sqlcmd的信息,请使用Get-Help cmdlet。
Get-Help Invoke-Sqlcmd –Full在本方案中,我们看到两种使用Invoke-Sqlcmd的方法。第一种是定义一个执行的查询语句。对此,你可以使用-Query选项。
Get-Help Invoke-Sqlcmd -Full In this recipe, we looked at two ways of using Invoke-Sqlcmd. The first is by specifying a query to run. For this, you should use the –Query option: #execute a passthrough query, and export to a CSV file Invoke-Sqlcmd ` -Query "SELECT * FROM Person.Person" ` -ServerInstance "$instanceName" ` -Database $dbName | Export-Csv -LiteralPath "C:\Temp\ResultsFromPassThrough.csv" ` -NoTypeInformation第二种方法,您需要运行一个SQL脚本,将参数切换为-InputFile。
#execute the SampleScript.sql, and display results to screen Invoke-SqlCmd ` -InputFile "C:\Temp\SampleScript.sql" ` -ServerInstance "$instanceName" ` -Database $dbName | Select FirstName, LastName, ModifiedDate | Format-Table