简体   繁体   中英

How to route SQL print output to log file?

Anyone who knows how to route print ' ' in an sql script to a logfile when using Invoke-Sqlcmd ?

I tried using sqlcmd -o someoutfile.txt , but it overwrites, it does not append to existing file. And if an SQL error occurs, only the error message is sent to file, not the print ' ' . When using Invoke-Sqlcmd | out-file someoutfile.txt -Append Invoke-Sqlcmd | out-file someoutfile.txt -Append , it appends only Write-Output and eventually SQL errors, but not the print ' ' in the sql script excuted.

Has anyone found a solution for this?

Invoke-SqlCmd implements T-SQL PRINT statements and RAISERROR using the verbose parameter. To capture verbose output, first you'll need to include the parameter in your call to invoke-sqlcmd ie invoke-sqlcmd -verbose and next you can do one of two things:

If you're using Powershell V3 or higher you can redirect verbose output:

invoke-sqlcmd -verbose 4>&1 | outfile someoutfile.txt

If you're using Powershell V2 you can't redirect verbose output to a file, however you can use start-transcript to send all screen output to a file. One gotcha with this approach--it will not work with SQL Agent Powershell job step. It will however work with a cmdexec job step which calls powershell.exe.

And one moment...

The command "Invoke-Sqlcmd" has a parameter -SeverityLevel. SeverityLevel specifies the lower limit for the error message severity level Invoke-Sqlcmd returns to the ERRORLEVEL PowerShell.

Invoke-Sqlcmd does not report severities for informational messages that have a severity of 10!

Severity Level 10: Status Information This is an informational message that indicates a problem caused by mistakes in the information the user has entered. Severity level 0 is not visible in SQL Server.

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