58230

How can I make a win32 command (sqlcommand) print its output to the console in PowerShell

Question:

I have a script that eventually calls this line

& sqlcmd.exe -S $DbHost -d $DbSchema -Q "do some crazy db change here"

Where "do some crazy db change here" will eventually be replaced by a dynamic bit of SQL/script.

When I run this whether it succeeds or not I see no output from sqlcmd.exe in my console. For user feedback I'd like to pipe this in real time to the console. How could I do that?

Answer1:

Here's how I have done it in the past, it makes use of events from StandardOut and StandardError. As these are executed asynchronously you are not entirely in control of the output (in terms of when it happens), but it should be close to what you need.

$SqlCommandArguments = @() $SqlCommandArguments += "-S $DbHost" $SqlCommandArguments += "-d $DbSchema" $SqlCommandArguments += "-Q `"do some crazy db change here`"" ExecuteProcess -FileName "SqlCmd.exe" -CommandArguments $SqlCommandArguments -Verbose:$VerbosePreference function ExecuteProcess { [cmdletbinding()] param ( [string]$FileName, [string[]]$CommandArguments ) Write-Verbose "$FileName $CommandArguments" $startInfo = New-Object System.Diagnostics.ProcessStartInfo $startInfo.FileName = $FileName $startInfo.Arguments = $CommandArguments $startInfo.RedirectStandardError = $true $startInfo.RedirectStandardOutput = $true $startInfo.UseShellExecute = $false $startInfo.CreateNoWindow = $true $process = New-Object System.Diagnostics.Process $process.StartInfo = $startInfo $eventOutputDataReceived = Register-ObjectEvent -InputObject $process -EventName OutputDataReceived -MessageData $VerbosePreference -Action { if ($($EventArgs.data)) { Write-Verbose $EventArgs.data -verbose:$event.MessageData } } $global:standardError = New-Object System.Text.StringBuilder $eventErrorDataReceived = Register-ObjectEvent -InputObject $process -EventName ErrorDataReceived -Action { if ($($EventArgs.data)) { $global:standardError.Append("$($EventArgs.data)`r`n") Write-Warning -message $EventArgs.data } } $process.Start() | Out-Null $process.BeginOutputReadLine() $process.BeginErrorReadLine() $process.WaitForExit() Unregister-Event -SourceIdentifier $eventOutputDataReceived.Name Unregister-Event -SourceIdentifier $eventErrorDataReceived.Name $exitCode = $process.ExitCode if ($exitCode -ne 0) { Write-Error $global:standardError.ToString() throw "$FileName Failed!" } }

Recommend

  • Is Console.SetOut wise to use when running tests in parallel?
  • Print Register in Assembly x86
  • Substitution Method - How to find two tags with a newline inbetween using Perl?
  • How to use the File System Events API in Swift?
  • Yii: any way to save the images in compressed form?
  • Configuring a TreeView which scans Local fie system to only include folders which have a file type
  • Catching the url path following a python cgi script?
  • PHP - sending email with attachment does not show message content
  • web shop (shopping cart) on google app engine
  • Laravel Impossible to Create Root Directory
  • HTML code to upload images
  • How to separate filename from path? basename() versus preg_split() with array_pop()
  • What does a hyphen at end of a term mean
  • Read a file in “chunks” using PHP
  • How to set download location via chrome api
  • Can XOR be expressed using SKI combinators?
  • removing last 3 characters on a file (file extension)
  • How to open html table in xls on click of a button
  • C# Excel interop - how to test if interop object is still working and performing a task?
  • Where these are stored?
  • Adding Object or changing its parameter programmatically in C# / ASP.Net
  • Write output of for loop to multiple files
  • Error processing multiple files
  • Tell Git to stop prompting me for conflicts when none really exist?
  • msbuild create itemgroup from property group
  • List images(01.png) and descriptions(01.txt) from directory
  • how to upload multiple files in c# windows application
  • How to install a .deb file on a jailbroken iphone programmatically?
  • Handling un-mapped Rest path
  • QLineEdit password safety
  • Nant, Vault & Windows Integrated Authentication
  • C# - Is there a limit to the size of an httpWebRequest stream?
  • Optimizing database types to compact database (SQLite)
  • Bug in WPF DataGrid
  • TFS: Get latest causes slow project reloading
  • Running a C# exe file
  • jQuery tmpl and DataLink beta
  • How can I estimate amount of memory left with calling System.gc()?
  • reshape alternating columns in less time and using less memory
  • Reading document lines to the user (python)