PowerShell ISE throws an error on git checkout

后端 未结 4 439
梦毁少年i
梦毁少年i 2020-12-06 17:14

In PowerShell, git checkout runs without any error message. In the ISE, while git checkout stills works, the ISE gives an error message.

         


        
相关标签:
4条回答
  • 2020-12-06 17:40

    There are few ways you can avoid these errors, none of them looks or feels 'natural'. First one uses error stream redirection and some logic around errors:

    $out = git ? 2>&1
    if ($?) {
        $out
    } else {
        $out.Exception
    }
    

    Second depends on the ErrorAction, that is available only for PowerShell constructs, so we need to build one first:

    & {
        [CmdletBinding()]
        param()
    
        git ?
    } -ErrorAction SilentlyContinue -ErrorVariable fail
    
    if ($fail) {
        $fail.Exception
    }
    

    In my ISEGit module I use latter to avoid error records 'leaking' to end user in uncontrolled manner.

    Finally you can 'fix it' (well, sort off...) by making sure you can a string in the end:

    "$(git ? 2>&1 )"
    

    Or something I would vote against as it will leave you unaware of any actual errors, setting global $ErrorActionPreference to SilentlyContinue - though this is not different from redirecting error stream to $null.

    0 讨论(0)
  • 2020-12-06 17:46

    It looks like you can now redirect stderr to stdout throughout your powershell script by simply setting an environment variable:

    $env:GIT_REDIRECT_STDERR = '2>&1'
    
    0 讨论(0)
  • 2020-12-06 17:55

    As specified here, adding -q after the command for quietness won't show these kind of errors.

    0 讨论(0)
  • 2020-12-06 17:55

    A profile ready Function-ized version of @BartekB's excellent answer...

    function Invoke-Git {
    <#
    .Synopsis
    Wrapper function that deals with Powershell's peculiar error output when Git uses the error stream.
    
    .Example
    Invoke-Git ThrowError
    $LASTEXITCODE
    
    #>
        [CmdletBinding()]
        param(
            [parameter(ValueFromRemainingArguments=$true)]
            [string[]]$Arguments
        )
    
        & {
            [CmdletBinding()]
            param(
                [parameter(ValueFromRemainingArguments=$true)]
                [string[]]$InnerArgs
            )
            C:\Full\Path\To\git.exe $InnerArgs
        } -ErrorAction SilentlyContinue -ErrorVariable fail @Arguments
    
        if ($fail) {
            $fail.Exception
        }
    
    }
    
    # Could shorten the function name. I instead alias it, for terseness.
    Set-Alias -Name git -Value Invoke-Git
    
    # Also alias the name with the extension, as it is called by some applications this way.
    Set-Alias -Name git.exe -Value Invoke-Git
    
    0 讨论(0)
提交回复
热议问题