简体   繁体   中英

Can't connect to database using PowerShell

I'm having issues with sqlps in my PowerShell script. I'm trying to select rows from a table and save them to a .csv file.

The query is

$TABLE="events"

Import-Module sqlps
$SQLquery='SELECT * FROM dbo.$TABLE'
$result=invoke-sqlcmd -query $SQLquery -HostName LOCALHOST -Password test -Username test
$result |export-csv c:\TEST.csv -notypeinformation

I get this error:

invoke-sqlcmd : Login failed for user 'test'.
At line:6 char:9
+ $result=invoke-sqlcmd -query $SQLquery -HostName LOCALHOST -Password  ...
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Invoke-Sqlcmd], SqlException
    + FullyQualifiedErrorId : SqlExectionError,Microsoft.SqlServer.Management. 
   PowerShell.GetScriptCommand

invoke-sqlcmd : 
At line:6 char:9
+ $result=invoke-sqlcmd -query $SQLquery -HostName LOCALHOST -Password  ...
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ParserError: (:) [Invoke-Sqlcmd], ParserException
    + FullyQualifiedErrorId : ExecutionFailureException,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand

Could anyone be able to help?

So the main issue was the query needed to be in "" quotes not '' quotes and the server needs to be told to explicitly allow Microsoft account logins and SQL logins. even if you have a user setup for sql login. the option is under properties/security/server authentication.

Im leaving this answer here for if anyone ever runs into this beginner issue as i have. Thanks for the help from the community to get this sorted so quickly

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM