'Git pull/Git clone returns blank value when using Invoke-Expression powershell

I am trying to run a Git pull and Git Clone command using Invoke-Expression mentioned below. In case there are any failures when running the below command, I wanted to capture the details on a variable so I can output the code accordingly. but unfortunately when using the below commands, it returns a blank variable with no output.

Invoke-Expression -Command "git pull https://$($UserName):$($Password)@$Gitpath --rebase" -OutVariable Gitresult 2>&1

Invoke-Expression -Command "git clone https://$($UserName):$($Password)@$Gitpath" -OutVariable Gitresult 2>&1

Kindly suggest, how I can get the output irrespective of success or failure events.

If there are any alternatives, please share.



Solution 1:[1]

git is kind of a weird cli as it makes use of stderr quite a bit. You don't need Invoke-Expression at all here:

$url = "https://${UserName}:${Password}@${Gitpath}"

$gitPullResult = git pull $url --rebase 2>&1
$gitCloneResult = git clone $url 2>&1

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Maximilian Burszley