凭据连接不起作用

时间:2012-03-23 17:56:08

标签: powershell load

我正在尝试在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

即使我使用正确的凭据,也会失败。有没有人有同样的问题? Invoke-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 个答案:

答案 0 :(得分:2)

要回答第二个问题:-),包含PSCredential的程序集已经加载。它是PowerShell所需的程序集。试试这个:

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

答案 1 :(得分:0)

试试这个(PsSnapin:SqlServerCmdletSnapin100):

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

Invoke-Sqlcmd -Query $Query -Serverinstance $SERVER -database $DataBase –Username “MyLogin” –Password $pwd