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
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?"
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') })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With