有没有办法在本地计算机上使用 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 上的脚本模块,以便您现在可以转到模块目录并执行
git clone https://github.com/ChrisMagnuson/InvokeSQL
,从那时起,当您调用时,invoke-sql 将自动加载去使用它(假设您使用 PowerShell v3 或更高版本)。
您可以使用
Invoke-Sqlcmd
cmdlet
Invoke-Sqlcmd -Query "SELECT GETDATE() AS TimeOfQuery;" -ServerInstance "MyComputer\MyInstance"
此函数将以 powershell 对象数组的形式返回查询结果,以便您可以在过滤器中使用它们并轻松访问列:
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
}
这是我在此博客上找到的示例。
$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 freeproccache
的不同 TSQL 语句。
如果您想在本地计算机而不是在 SQL Server 上下文中执行此操作,那么我将使用以下内容。我们公司就是用的。
$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 和 $Query 变量即可开始操作。
我不确定我们最初是如何发现这一点的,但有一些非常相似的东西这里。
没有运行 SQL 查询的内置“PowerShell”方式。 如果您安装了 SQL Server 工具,您将获得一个 Invoke-SqlCmd cmdlet。
由于 PowerShell 是基于 .NET 构建的,因此您可以使用 ADO.NET API 来运行查询。
Invoke-Sqlcmd -Query "sp_who" -ServerInstance . -QueryTimeout 3
为了避免使用 varchar 参数进行 SQL 注入,您可以使用
function sqlExecuteRead($connectionString, $sqlCommand, $pars) {
$connection = new-object system.data.SqlClient.SQLConnection($connectionString)
$connection.Open()
$command = new-object system.data.sqlclient.sqlcommand($sqlCommand, $connection)
if ($pars -and $pars.Keys) {
foreach($key in $pars.keys) {
# avoid injection in varchar parameters
$par = $command.Parameters.Add("@$key", [system.data.SqlDbType]::VarChar, 512);
$par.Value = $pars[$key];
}
}
$adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command
$dataset = New-Object System.Data.DataSet
$adapter.Fill($dataset) | Out-Null
$connection.Close()
return $dataset.tables[0].rows
}
$connectionString = "connectionstringHere"
$sql = "select top 10 Message, TimeStamp, Level from dbo.log " +
"where Message = @MSG and Level like @LEVEL"
$pars = @{
MSG = 'this is a test from powershell'
LEVEL = 'aaa%'
};
sqlExecuteRead $connectionString $sql $pars
您可以使用最好的 SQL Server 模块:DBATOOLS。您还可以从对多个 sql 实例运行查询中受益。
Install-Module dbatools -Scope CurrentUser
$sql = 'SQL1','SQL1\INSTANCE1','SQL2'
$query = "SELECT 'This query would run on all SQL instances'"
Invoke-DbaQuery -SqlInstance $sqlinstances -Query $query -AppendServerInstance
您甚至可以根据需要格式化字符串并传递参数。
case "ADDSQLSERVERUSER":
//0 = coprorateName;
//1 = user password
//2 = servername
command = @"$sqlQuery = Use JazzUWS_'{0}'
Create login UWSUser_'{0}' with password='{1}';
Create user UWSUser_'{0}' for login UWSUser_'{0}';
Grant Execute to UWSUser_'{0}';
Use ReportSvrUWS_'{0}'
Create user UWSUser_'{0}' for login UWSUser_'{0}';
Grant Execute to UWSUser_'{0}';
Invoke-Sqlcmd -Query $sqlQuery -ServerInstance '{2}'";
break;
用于远程执行的C#代码(您可以组织您的方式)
string script = PowershellDictionary.GetPowershellCommand("ADDSQLSERVERUSER");
script = String.Format(script, this.CorporateName, password, this.SQLServerName)
PowerShellExecution.RunScriptRemote(_credentials.Server, _credentials.Username, _credentials.Password, new List<string> { script });
我最终不得不使用 IP 地址,因为“Mycomputer\myinstance”无法正常工作。我还必须传递凭据,因为我没有设置域林。
Invoke-Sqlcmd -Query "SELECT GETDATE() AS TimeOfQuery" -ServerInstance "127.0.0.1,1433" -Username "username" -Password 'passowrd'
此外,您可能应该将密码存储在计算机上的某个位置或从主机获取密码并登录
$pw = Read-Host -AsSecureString
请记住,像这样使用纯文本是不好的做法,但这对我的用例有用