繁体   English   中英

如何使用PowerShell查询SQL Server?

[英]How to query SQL Server using PowerShell?

我在网上找到了一些代码,但到目前为止,我无法将其连接到我的SQL Server数据库。 我已在此网站上找到这封信: https : //blogs.msdn.microsoft.com/walzenbach/2010/04/14/how-to-enable-remote-connections-in-sql-server-2008/

我允许远程连接,将端口1433添加到防火墙等。然后从PowerShell ISE运行以下代码:

    $dataSource = “\\SCCM12-01\MSSQLSERVER”
    $user = “MyID\OurDomain.org”
    $pwd = “MyPassword”
    $database = “CM1”
    $connectionString = “Server=$dataSource;uid=$user; pwd=$pwd;Database=$database;Integrated Security=False;”

    $connection = New-Object System.Data.SqlClient.SqlConnection
    $connection.ConnectionString = $connectionString
    $connection.Open()

运行此命令时,出现以下错误。

使用“ 0”参数调用“ Open”的异常:“建立与SQL Server的连接时发生与网络相关或特定于实例的错误。找不到服务器或无法访问该服务器。请验证实例名称是否正确并且该SQL Server已配置为允许远程连接。(提供者:SQL网络接口,错误:25-连接字符串无效)”

如果您要执行简单的查询,建议您选择Select-SQLView powershell模块。 它允许快速从表或视图中选择行。 它存储您的数据库和服务器名称,因此您不必每次都提供此值。

与往常一样,您可以将结果推送到表或GridView。

如果需要更复杂的查询,请使用SQLCommands模块。

选择SQLView

不知道为什么会收到此错误。 您可以参考此链接https://github.com/Tervis-Tumbler/InvokeSQL

你可以试试这个

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  
}

该错误消息实际上解释了问题所在:

“ SQL网络接口,错误:25- 连接字符串无效 ”。

连接字符串上有问题。 掩盖了大多数细节之后,很难说什么。 也许聪明的报价破坏了事情? 也许您在密码中输入了引号字符? 无论如何,看来您的用户ID 参数无效

$connectionString = “Server=$dataSource;uid=$user; pwd=$pwd;Database=$database;Integrated Security=False;”

尝试User Id代替uid

Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;

不使用数据库登录名时,只需将“集成安全性”更改为“真”即可

**Integrated Security=True**

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM