2017-08-24 91 views
1

我試圖將我的腳本連接到數據庫。 以前我做它:來自powershell的SQL連接

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'." 

當然,我敢肯定的憑據是正確的。 這可能是兩種連接模式之間的區別?在連接字符串中提供

回答

0

憑據:

如果您有現有的認證對象,你可以使用它像這樣:

$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()