Can't connect to database using PowerShell

2.4k views Asked by At

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?

1

There are 1 answers

0
Andrea Visnenza Andy On

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