2012-03-23 91 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