Git clone: Redirect stderr to stdout but keep errors being written to stderr

前端 未结 7 591
广开言路
广开言路 2020-11-27 21:11

git clone writes its output to stderr as documented here. I can redirect this with the following command:

git clone https://myrepo          


        
7条回答
  •  春和景丽
    2020-11-27 21:22

    I have modified the Invoke-Git to suit my needs better.

    From many of the posts that I have read while looking for a solution I'm guessing more than a few people can use this.

    Enjoy.

    This version that will:

    • Execute the Git command passed in (assumes Git is in the execution path already.)
    • If all goes well then all output (stdout and stderr) is displayed on the host, NOT via stderr.
    • Check the $LASTEXITCODE to see if there was actually an error. If there was an error then all the output is thrown to the caller to deal with.
    <#
    .Synopsis
        Invoke git, handling its quirky stderr that isn't error
    
    .Outputs
        Git messages
    
    .Example
        Invoke-Git push
    
    .Example
        Invoke-Git "add ."
    #>
    function Invoke-Git
    {
    param(
    [Parameter(Mandatory)]
    [string] $Command )
    
        try {
            # I could do this in the main script just once, but then the caller would have to know to do that 
            # in every script where they use this function.
            $old_env = $env:GIT_REDIRECT_STDERR
            $env:GIT_REDIRECT_STDERR = '2>&1'
    
            Write-Host -ForegroundColor Green "`nExecuting: git $Command "
            $output = Invoke-Expression "git $Command "
            if ( $LASTEXITCODE -gt 0 )
            {
                # note: No catch below (only the try/finally). Let the caller handle the exception.
                Throw "Error Encountered executing: 'git $Command '"
            }
            else
            {
                # because $output probably has miultiple lines (array of strings), by piping it to write-host we get multiple lines.
                $output | Write-Host 
            }
        }
        # note: No catch here. Let the caller handle it.
        finally
        {
            $env:GIT_REDIRECT_STDERR = $old_env
        }
    }
    

提交回复
热议问题