Powershell Invoke-Sqlcmd capture verbose output
So I know this is a little unrelated, but I needed to capture "RAISERROR" and "PRINT" statements in a separate variable then the row data. Here is how I did it:
$Messages = %{ $Rows = Invoke-Sqlcmd -Query "PRINT 'Hello World!';" -ServerInstance $Server -verbose} 4>1
It row data from Invoke-SqlCmd is on STDOUT which is consumed by $Rows the verbose output continues on the pipe and is redirected into STDOUT (which, thanks to $Rows is empty). The only thing in STDOUT to hand to $Messages is the Verbose output. Whew!
It's a little further complicated in that to get to the data it's now on $Messages.Message.
According to Capture Warning, Verbose, Debug and Host Output via alternate streams:
...if I wanted to capture verbose output in a script:
stop-process -n vd* -verbose 4>&1 > C:\Logs\StoppedProcesses.log
So, you would do something like
(Invoke-Sqlcmd -Query "PRINT 'Hello World!';" -ServerInstance $Server -verbose) 4> c:\temp\myoutput.txt
Where 4 is the "verbose" stream.
Please try:
Invoke-Sqlcmd -Query "PRINT 'Hello World!';" -ServerInstance $Server -verbose > D:\SqlLog.txt 2>&1
I found it at
Since capturing verbose output is not something one can do easily through the native constructs of the PowerShell host, you can always use the programatic access to the PowerShell object. You can then gain access to the five different streams of information:
> $ps = [PowerShell]::Create()
> [ref]$e = New-Object System.Management.Automation.Runspaces.PSSnapInException
> $ps.Runspace.RunspaceConfiguration.AddPSSnapIn( "SqlServerCmdletSnapin100", $e ) | Out-Null
> $ps.AddCommand( "Invoke-Sqlcmd" ).AddParameter( "Query", "Print 'hello world'" ).AddParameter( "Verbose" )
> $ps.Invoke()
> $ps.Streams
Error : {}
Progress : {}
Verbose : {hello world}
Debug : {}
Warning : {}
> $ps.Streams.Verbose | % { $_.Message | Out-File -Append D:\SqlLog.txt }
> cat D:\SqlLog.txt
hello world