Powershell查询SQL数据库资料

  

豆子对SQL Server自带的sqlps模块并不熟悉。昨天发现琼斯不提供的一个SQL模块,理论上支持任何兼容ODBC驱动程序的数据库(MySQL,该软件,甲骨文等等),原理就是调用。网框架的一些底层函数。使用起来很方便顺手,也不需要学习新的技能。


https://technet.microsoft.com/zh-cn/magazine/hh855069.aspx


下载以后,发现这个模块其实就只包括了两个函数,一个用来查询,另外一个用来修改删除。两个函数都只有3个参数,分别是connectionString,需要执行SQL语的句,以及是否为。状态"置疑"第一个的格式根据数据库有所不同,可以去http://www.connectionstrings.com/ 看对应的例子。第二个就是真正执行SQL语的句,最后一个其实是个布尔值,如果输入了这个参数就是真,没输入就是假。


function  Get-DatabaseData  {   ,,,(CmdletBinding ())   ,,,param  (   ,,,,,,,[string] connectionString美元,   ,,,,,,,(字符串)查询,美元   ,,,,,,,[转]isSQLServer美元   ,,,)   ,,,if  (isSQLServer美元),{   ,,,,,,,Write-Verbose “SQL 拷贝;Server 模式”   ,,,,,,,connection 美元;=,New-Object  -TypeName    ,,,,,,,,,,System.Data.SqlClient.SqlConnection   ,,,},{else    ,,,,,,,Write-Verbose “OleDB 拷贝模式”   ,,,,,,,connection 美元;=,New-Object  -TypeName    ,,,,,,,,,,System.Data.OleDb.OleDbConnection   ,,,}   ,,,connection.ConnectionString 美元;=,connectionString美元   ,,,command 美元;connection.CreateCommand美元=,()   ,,,command.CommandText 美元;美元=,查询   ,,,if  (isSQLServer美元),{   ,,,,,,,adapter 美元;=,New-Object  -TypeName    ,,,,,,,System.Data.SqlClient.SqlDataAdapter  $命令   ,,,},{else    ,,,,,,,adapter 美元;=,New-Object  -TypeName    ,,,,,,,System.Data.OleDb.OleDbDataAdapter  $命令   ,,,}   ,,,dataset 美元;=,New-Object  -TypeName  System.Data.DataSet   ,,,adapter.Fill美元($数据集)   ,,,美元dataset.Tables [0]   ,,,美元connection.close ()   }         function  Invoke-DatabaseQuery  {   ,,,[CmdletBinding SupportsShouldProcess=$真的,   ,,,,,,,,,,,,,,,,,,ConfirmImpact='低'))   ,,,param  (   ,,,,,,,[string] connectionString美元,   ,,,,,,,(字符串)查询,美元   ,,,,,,,[转]isSQLServer美元   ,,,)   ,,,if  (isSQLServer美元),{   ,,,,,,,Write-Verbose “SQL 拷贝;Server 模式”   ,,,,,,,connection 美元;=,New-Object  -TypeName    ,,,,,,,,,,System.Data.SqlClient.SqlConnection   ,,,},{else    ,,,,,,,Write-Verbose “OleDB 拷贝模式”   ,,,,,,,connection 美元;=,New-Object  -TypeName    ,,,,,,,,,,System.Data.OleDb.OleDbConnection   ,,,}   ,,,connection.ConnectionString 美元;=,connectionString美元   ,,,command 美元;connection.CreateCommand美元=,()   ,,,command.CommandText 美元;美元=,查询   ,,,if  ($ pscmdlet.shouldprocess(查询)美元),{   ,,,,,,,美元connection.Open ()   ,,,,,,,美元command.ExecuteNonQuery ()   ,,,,,,,美元connection.close ()   ,,,}   }



下载脚本之后,重命名然后拷贝到$ env: psmodulepath对应的路径上就可以使用了


 Powershell查询SQL数据库资料

现在看看怎么使用。


例如:豆子想查询一下某个数据库的备份记录。首先登陆MSSQL2012表达的管理界面,利用t - SQL语句查询看看应该的效果。


 Powershell查询SQL数据库资料


把t - SQL的语句拷贝下来,作为传入的字符串参数,如下所示,调用第一个查询的函数


Import-Module  db   ConnectionString 美元;=,=sophos521服务器=sydav01 \ Sophos;数据库;trusted_connection=True;”   查询美元="   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null

Powershell查询SQL数据库资料