Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to find out if Git is installed via Powershell?

Tags:

git

powershell

I have this short combination of cmdlets(?) that tells by counting how many returns I get, but it only works if Git was installed in the $Env:Path.

I want to use git rev-parse --short HEAD, but check if it is installed beforehand in a PS script.

# $gitInstalled = "git" | Get-Command -CommandType Application -ErrorAction SilentlyContinue | measure; 
# Write-Host $count.Count; 

I realize it pretty much answers the question by itself, But I want to know if there is another way, more efficient or broadly covering, to find out if Git is installed?

Edit: So we can shorten the command to just

# $gitInstalled = Get-Command -ErrorAction SilentlyContinue git
like image 720
Brenden Cai Avatar asked Sep 12 '25 07:09

Brenden Cai


2 Answers

You can just see if the command is available:

try
{
    git | Out-Null
   "Git is installed"
}
catch [System.Management.Automation.CommandNotFoundException]
{
    "No git"
}

This also happens to cover the additional question, "Is git in $env:path?"

like image 172
Joshua Thornton Avatar answered Sep 13 '25 23:09

Joshua Thornton


You can query the registry for the installed programs by looking at the Uninstall keys:

Function Test-IsGitInstalled
{
    $32BitPrograms = Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*
    $64BitPrograms = Get-ItemProperty     HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*
    $programsWithGitInName = ($32BitPrograms + $64BitPrograms) | Where-Object { $null -ne $_.DisplayName -and $_.Displayname.Contains('Git') }
    $isGitInstalled = $null -ne $programsWithGitInName
    return $isGitInstalled
}

Or as a one-liner:

$isGitInstalled = $null -ne ( (Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*) + (Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*) | Where-Object { $null -ne $_.DisplayName -and $_.Displayname.Contains('Git') })
like image 44
bergmeister Avatar answered Sep 13 '25 23:09

bergmeister