如何从PowerShell运行SQL Server查询?

有没有办法在我的本地机器上使用Powershell在SQL Server上执行任意查询?

对于需要使用.net和PowerShell(不需要额外安装SQL工具)的人来说,这里是我使用的函数:

function Invoke-SQL { param( [string] $dataSource = ".\SQLEXPRESS", [string] $database = "MasterData", [string] $sqlCommand = $(throw "Please specify a query.") ) $connectionString = "Data Source=$dataSource; " + "Integrated Security=SSPI; " + "Initial Catalog=$database" $connection = new-object system.data.SqlClient.SQLConnection($connectionString) $command = new-object system.data.sqlclient.sqlcommand($sqlCommand,$connection) $connection.Open() $adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command $dataset = New-Object System.Data.DataSet $adapter.Fill($dataSet) | Out-Null $connection.Close() $dataSet.Tables } 

我一直在使用这个这么久,我不知道是谁写了哪些部分,但这是从其他的例子中提炼出来的,但是简化为清楚,正是没有额外的依赖或特性需要的东西。

我经常使用和共享这个,我把它变成了GitHub上的一个脚本模块,这样你就可以进入你的modules目录并执行git clone https://github.com/ChrisMagnuson/InvokeSQL并从这一点转发invoke- sql会自动加载,当你去使用它(假设你使用PowerShell的v3或更高版本)。

您可以使用Invoke-Sqlcmd cmdlet

 Invoke-Sqlcmd -Query "SELECT GETDATE() AS TimeOfQuery;" -ServerInstance "MyComputer\MyInstance" 

http://technet.microsoft.com/en-us/library/cc281720.aspx

这是我在这个博客上find的一个例子。

 $cn2 = new-object system.data.SqlClient.SQLConnection("Data Source=machine1;Integrated Security=SSPI;Initial Catalog=master"); $cmd = new-object system.data.sqlclient.sqlcommand("dbcc freeproccache", $cn2); $cn2.Open(); if ($cmd.ExecuteNonQuery() -ne -1) { echo "Failed"; } $cn2.Close(); 

据推测,你可以用dbcc freeproccachereplace一个不同的TSQL语句。

这个函数将返回一个查询的结果作为一个PowerShell对象的数组,所以你可以很容易地在filter和访问列中使用它们:

 function sql($sqlText, $database = "master", $server = ".") { $connection = new-object System.Data.SqlClient.SQLConnection("Data Source=$server;Integrated Security=SSPI;Initial Catalog=$database"); $cmd = new-object System.Data.SqlClient.SqlCommand($sqlText, $connection); $connection.Open(); $reader = $cmd.ExecuteReader() $results = @() while ($reader.Read()) { $row = @{} for ($i = 0; $i -lt $reader.FieldCount; $i++) { $row[$reader.GetName($i)] = $reader.GetValue($i) } $results += new-object psobject -property $row } $connection.Close(); $results } 

如果你想在你的本地机器上而不是在SQL服务器上下文,那么我会使用下面的代码。 这是我们在我的公司使用的。

 $ServerName = "_ServerName_" $DatabaseName = "_DatabaseName_" $Query = "SELECT * FROM Table WHERE Column = ''" #Timeout parameters $QueryTimeout = 120 $ConnectionTimeout = 30 #Action of connecting to the Database and executing the query and returning results if there were any. $conn=New-Object System.Data.SqlClient.SQLConnection $ConnectionString = "Server={0};Database={1};Integrated Security=True;Connect Timeout={2}" -f $ServerName,$DatabaseName,$ConnectionTimeout $conn.ConnectionString=$ConnectionString $conn.Open() $cmd=New-Object system.Data.SqlClient.SqlCommand($Query,$conn) $cmd.CommandTimeout=$QueryTimeout $ds=New-Object system.Data.DataSet $da=New-Object system.Data.SqlClient.SqlDataAdapter($cmd) [void]$da.fill($ds) $conn.Close() $ds.Tables 

只需填写$ ServerName$ DatabaseName$ Queryvariables,你应该很好。

我不确定我们最初是如何发现这一点的,但是这里有一些非常相似的东西 。

没有内置的运行SQL查询的“PowerShell”方法。 如果安装了SQL Server工具 ,则会得到一个Invoke-SqlCmd cmdlet。

由于PowerShell构build于.NET上,因此可以使用ADO.NET API来运行查询。

 Invoke-Sqlcmd -Query "sp_who" -ServerInstance . -QueryTimeout 3