SQL连接来自powershell

时间:2017-08-24 10:35:44

标签: sql-server powershell sqlcmd

我试图将我的脚本连接到数据库。 以前我用它做过:

psexec \\servername -accepteula sqlcmd.exe -U username -P password -S database -Q query

现在,我想将其转换为powershell代码。 我试过这个:

Enter-PSSession servername
$SQLCred = New-Object System.Data.SqlClient.SqlCredential("username","password")
$Connection = New-Object System.Data.SqlClient.SqlConnection("Database",$SQLCred)
$Connection.Open()

但我总是得到这个错误:

Exception calling "Open" with "0" argument(s): "Login failed for user 'username'."

当然,我确定凭据是正确的。 这可能是两种连接模式之间的区别?

2 个答案:

答案 0 :(得分:0)

凭据在连接字符串中提供:

$instance = "myInstance"
$userId = "myUserId"
$password = "myPassword"

$connectionString = "Data Source=$instance;Integrated Security=SSPI;Initial Catalog=master; User Id=$userId; Password=$password;"

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

如果您有现有的凭据对象,可以像这样使用它:

$cred = New-Object System.Data.SqlClient.credential($userId, $password)
$connectionString = "Data Source=$Instance;Integrated Security=SSPI;Initial Catalog=master; User Id = $($cred.username); Password = $($cred.GetNetworkCredential().password);"
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
$connection.Open()

答案 1 :(得分:0)

    $SQLCredential = New-Object System.Data.SqlClient.SqlCredential($SQLUserName, $SQLPassword)
    $SQLServerConnection = New-Object System.Data.SqlClient.SqlConnection("Data Source=$SQLInstanceName; Initial Catalog=MASTER")
    $SQLServerConnection.Credential = $SQLCredential
    try
    {
        $SQLServerConnection.Open()
    }