Powershell only executes first sql statement in the sql file

Hello Everyone,

I am trying execute two simple SELECT statements placed in a sql file and then trying to execute the sql file via powershell and dumping the results in a text file using the below code. However it only executes the first select statement.

$SQL = Get-Content -Path “C:\SQL Reports\Daily Checks.sql”

Invoke-Sqlcmd -Username “" -Password "” -ServerInstance “" -Database "” -Query $SQL | Out-File -FilePath “C:\SQL Reports\powershelloutput.txt”

 

It is just printing the results of the first sql in the output file and not the second one.

Can someone please guide what may be wrong or if the above method is not supposed to execute multiple sqls in a sql file.

The simple sql statements are like below

SELECT * FROM TABLE1

SELECT * FROM TABLE2

 

Thanks,

AK

Just taking a guess, what if you add -Raw to the Get-Content command?

To add to Doug’s comment. By default Get-Content would return an array of strings where each line of the text file is a member of that array. When you add the -Raw switch it returns a single string with the entire contents of the file including line breaks.

I believe the -Query parameter expects a single SQL statement. If that is true then you shouldn’t use the -Raw switch and iterate over the array like this:

$SQL = Get-Content -Path “C:\SQL Reports\Daily Checks.sql”

foreach ($item in $SQL)
{
    Invoke-Sqlcmd -Username “*” -Password “*” -ServerInstance “*” -Database “*” -Query $item | 
        Out-File -FilePath “C:\SQL Reports\powershelloutput.txt” -Append
}

 

Or…per the documentation…

Example 2: Invoke commands in a script file and save the output in a text file
PowerShell

PS C:\> Invoke-Sqlcmd -InputFile "C:\ScriptFolder\TestSqlCmd.sql" | Out-File -FilePath "C:\ScriptFolder\TestSqlCmd.rpt"
Output sent to TestSqlCmd.rpt.

This command reads a file containing Transact-SQL statements and SQLCMD commands, runs the file, and writes the output to another file.

The output file may contain proprietary information, so you should secure the output files with the appropriate NTFS permissions.

Good call Rob:

Get-Help Invoke-Sqlcmd

Get-Help … it works every time. If you don’t believe me, ask the god of thunder. :slight_smile: