首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在PowerShell中让win32命令( the命令)将其输出打印到控制台

如何在PowerShell中让win32命令( the命令)将其输出打印到控制台
EN

Stack Overflow用户
提问于 2013-12-06 08:29:59
回答 1查看 193关注 0票数 0

我有一个脚本,它最终调用这行代码

代码语言:javascript
复制
& sqlcmd.exe -S $DbHost -d $DbSchema -Q "do some crazy db change here"  

其中“在这里做一些疯狂的数据库更改”最终将被SQL/脚本的动态比特所取代。

当我运行此命令时,无论它是否成功,我在控制台中都看不到来自sqlcmd.exe的输出。对于用户反馈,我想通过管道将其实时发送到控制台。我怎么能这么做呢?

EN

回答 1

Stack Overflow用户

发布于 2013-12-06 20:25:49

这是我过去的做法,它利用了来自StandardOut和StandardError的事件。因为这些都是异步执行的,所以您不能完全控制输出(就发生的时间而言),但它应该接近您所需要的。

代码语言:javascript
复制
$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!"
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20413700

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档