Home > Software engineering >  How do I send a username and password to git's credential user prompt from my powershell script
How do I send a username and password to git's credential user prompt from my powershell script

Time:04-13

I am using a script to checkout and update a list of branches. I am able to retrieve git credentials from the Windows Credential Manager and I need to respond to the prompt for git credentials using them.

How do I send text to the git user prompt from my script? I have tried ECHO and piping the text directly to the git call but neither method is working (the prompt still appears and nothing is typed in).

[PSCredential]$cred = Get-StoredCredential gitCred
$cur_head = "$(git rev-parse --abbrev-ref HEAD)"
$cred.Username |  git pull origin ${cur_head} -q

or

ECHO $cred.Username |  git pull origin ${cur_head} -q

Note: I am using the windows credential manager to store my git credentials, I do not want to put them in any other credential manager

CodePudding user response:

In a couple of my scripts I use this:

$env:GIT_USER="."
$env:GIT_PASS=$token
Invoke-Git config --global credential.helper "!f() { echo \`"username=`${GIT_USER}`npassword=`${GIT_PASS}\`"; }; f"

To pass an arbitrary username/password from the environment of the running powershell session. The code above passes a Personal Access Token, but you can easily set the environment variables with a different value.

You could also install the Git Cretential Manager (Core), which would automatically fetch the creds from the windows credential manager.

For those interested in the implementation of Invoke-Git:

function Invoke-Git {
<#
.Synopsis
Wrapper function that deals with PowerShells 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
        )
        if ($isDebug) { "git $InnerArgs" }
        git $InnerArgs
    } -ErrorAction SilentlyContinue -ErrorVariable fail @Arguments

    if ($fail) {
        $fail.Exception
    }

}
  • Related