如何使用不同的域用户凭据在Powershell中执行sqlcmd

时间:2017-09-14 08:08:18

标签: authentication sqlcmd invoke-command

我有一个SQL脚本,我需要使用从注册表中检索的凭据来执行。

将它们存储在注册表中

$secureCredential = Get-Credential -Message "Enter service account credential as DOMAIN\Username format."
$credentialName = Read-Host "Enter a name for this credential"
$securePasswordString = $secureCredential.Password | ConvertFrom-SecureString
$userNameString = $secureCredential.Username
New-Item -Path HKLM:\Software\$OrgName\Credentials\$credentialName
New-ItemProperty -Path HKLM:\Software\$OrgName\Credentials\$credentialName -PropertyType String -Name UserName -Value $userNameString
New-ItemProperty -Path HKLM:\Software\$OrgName\Credentials\$credentialName -PropertyType String -Name Password -Value $securePasswordString

要检索

$secureCredUserName = Get-ItemProperty -Path HKLM:\Software\MyCompany\Credentials\TfsBuildAgent -Name UserName
$secureCredPassword = Get-ItemProperty -Path HKLM:\Software\MyCompany\Credentials\TfsBuildAgent -Name Password
$dbCreatorUserName = $secureCredUserName.UserName
$dbCreatorPassword = ConvertTo-SecureString -String $secureCredPassword.Password

由于DB权限,必须使用这些凭据执行脚本。所以 我从注册表中检索它们:

$secureCredUserName = Get-ItemProperty -Path HKLM:\Software\MyCompany\Credentials\TfsBuildAgent -Name UserName
$secureCredPassword = Get-ItemProperty -Path HKLM:\Software\MyCompany\Credentials\TfsBuildAgent -Name Password
$dbCreatorUserName = $secureCredUserName.UserName
$dbCreatorPassword = ConvertTo-SecureString -String $secureCredPassword.Password
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $using:dbCreatorUserName, $using:dbCreatorPassword

然后尝试使用Invoke-Command执行sqlcmd,以便我可以提供域凭据:

Invoke-Command -ComputerName $env:ComputerName -EnableNetworkAccess -Credential $credential -Authentication Default {sqlcmd.exe -b -S 'db-systest' -i C:\Database\Database_Package.sql -E -v }

但是得到错误:

Microsoft ODBC Driver 11 for SQL Server : Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'..

我已经尝试了 - 身份验证默认和-Authentication谈判, 服务器不支持Kerberos,域策略禁止使用CredSSP。

0 个答案:

没有答案