0

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?

9
  • Take a look at Sql Server's log file. It will contain more detailed an error message. Commented Jun 26, 2018 at 8:45
  • 2
    Single quotes for the $SQLQuery variable mean that it literally looks for $TABLE, not the events table I think you meant. Oh, and the password is probably wrong, I didn't read that bit properly! Commented Jun 26, 2018 at 8:46
  • Check by adding Write-Host $SQLQuery, that'll show you what the variable contains Commented Jun 26, 2018 at 8:47
  • Where do you specify the database to which you connect? Are you connecting to a specific SQL Server instance ? Commented Jun 26, 2018 at 8:47
  • 1
    Where's the database located? The example you're running assumes the database is on the same machine that the code is running on. If that's correct then the credentials must be wrong. Also the -Database switch is usually required as @DavidBrabant said Commented Jun 26, 2018 at 8:57

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.