如何使用win32命令(sqlcommand)将其输出打印到PowerShell中的控制台

时间:2013-12-06 00:29:59

标签: sql-server-2008 powershell sqlcmd

我有一个最终调用此行的脚本

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

“在这里做一些疯狂的数据库更改”最终将被动态的SQL /脚本替换。

当我运行它是否成功时,我在控制台中看不到sqlcmd.exe的输出。对于用户反馈,我想将其实时传输到控制台。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

以下是我过去的工作方式,它使用了StandardOut和StandardError中的事件。由于这些是异步执行的,因此您无法完全控制输出(就何时发生而言),但它应该接近您所需要的。

$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!"
    }
}