2012-03-23 123 views
1

我試圖在PowerShell腳本中使用憑據連接。我想:憑據連接不起作用

$credential = Get-Credential 

$credential = $host.ui.PromptForCredential("Need credentials", "Please enter your user name and password.", "", "Domain") 

但是,當我執行查詢時,我得到以下信息:

Invoke-SqlQuery -Query $Query -Server $SERVER -database $DataBase -credential $credential 
Exception calling "Open" with "0" argument(s): "Login failed for user '\sa'." 
\Modules\InvokeSqlQuery\InvokeSqlQuery.psm1:155 char:14 
+  $cnn.Open <<<<(); 
    + CategoryInfo   : NotSpecified: (:) [], MethodInvocationException 
    + FullyQualifiedErrorId : DotNetMethodException 

即使我用正確的憑據,它失敗。有沒有人有同樣的問題? 調用,調用類SqlQuery

$cnn = New-SqlConnection $Server $Database $Credential $ConnectionTimeout 

其產生的誤差。

順便說一句,我想知道如何加載該組件:

new-object [System.Management.Automation.PSCredential] 
New-Object : Cannot find type [[System.Management.Automation.PSCredential]]: make sure the assembly containing this type is loaded. 

感謝。

回答

2

要回答第二個問題:-),包含PSCredential的程序集已經加載。它是PowerShell所需的程序集。試試這個:

$username = ConvertTo-SecureString username -AsPlainText -Force 
$password = ConvertTo-SecureString pass!word -AsPlainText -Force 
$cred = new-object management.automation.pscredential $username,$password 
+2

一個絕妙的技巧,看看集加載是什麼'[應用程序域] :: CurrentDomain.GetAssemblies()|選擇ManifestModule | Sort ManifestModule' – 2012-03-23 19:36:46

+1

另一招是'[appdomain] :: CurrentDomain.GetAssemblies()|哪裏位置| Foreach {$ _。GetExportedTypes()} |名稱 - 匹配PSCredential |格式 - 表名稱,程序集-AutoSize' – 2012-03-23 20:41:25

+0

確實,非常好:-) – 2012-03-23 21:00:32

0

試試這個(PsSnapin:SqlServerCmdletSnapin100):

$pwd = read-host -AsSecureString -Prompt "Password" 

Invoke-Sqlcmd -Query $Query -Serverinstance $SERVER -database $DataBase –Username 「MyLogin」 –Password $pwd 
+0

找不到與參數名稱「用戶名」匹配的參數。 事實上,所允許的參數是: 調用-SqlQuery類[[-Query] ] [-File ] [α參數] [-Server ] [-Database ] [-Credential ] [-IncludeRecordSetIndex ] [-IncludeReco rdsCount] [-ConnectionTimeout ] [-ExecutionTimeout ] [-WhatIf] [-Confirm] [-UseTransaction] [] 這就是爲什麼我想實例化憑據。 – TTT 2012-03-26 17:28:25

+0

是的,困惑的cmdlet沒有測試!編輯我的答案.. – 2012-03-26 19:16:44