Powershell Invoke-Sqlcmd Login Failed

佐手、 提交于 2020-01-15 07:02:17

问题


I am trying to run a sql query from powershell for Windows SQL Server 2008 R2. It looks like the code is failing to pass SQL Server Authentication credentials to run the sqlcmd correctly. I am running this first part directly from powershell, not as a script.

Set-Location SQLServer:\SQL\Server\
Invoke-sqlcmd "SELECT DB_NAME() AS hist;" -username "username" -password "p@ss"

I receive error, Login failed for user 'username'. The ideal end result for the code format would look more like this. Same resulting error.

$path = "sqldbdump.csv"
$server = "serveronlocalhost"
$db = "hist"
$Query = @"
SELECT * From alarms;
"@
Invoke-Sqlcmd -ServerInstance $server -Database $db -Username $username -Password $pw -Query $Query | Export-CSV $path

I have also tried convert-tosecurestring -asplaintext with no success.

$pw = convertto-securestring -AsPlainText -Force -String "p@ss"

回答1:


Never use double quotes for a variable containing a password because special characters are interpreted (the same for username containing special characters). It is not the case with single quoted strings.

For example, this password will cause an authentification error because the character $ is evaluated:

$pw = "p@ss$ord!"

But if you use single quotes, it will work:

$pw = 'p@ss$ord!'

Please note that the same principle applies to command lines, so this wil not work:

Invoke-Sqlcmd ... -Password "p@ss$ord!"

You should write:

Invoke-Sqlcmd ... -Password 'p@ss$ord!'


来源:https://stackoverflow.com/questions/22335651/powershell-invoke-sqlcmd-login-failed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!