2017-10-14 64 views
0

我有这个简短的cmdlet(?)组合,它通过计算我得到的返回次数来告诉它,但只有当Git安装在$ Env:Path中时才有效。试图找出Git是否通过Powershell安装?

我想使用git rev-parse --short HEAD,但请检查它是否事先安装在PS脚本中。

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

我意识到它几乎答案本身的问题,但我想知道是否有另一种方式,更高效的或宽覆盖,以找出是否安装了Git的?

编辑:所以我们可以缩短命令只

# $gitInstalled = Get-Command -ErrorAction SilentlyContinue git 
+0

在Powershell中运行'git version'? – ElpieKay

+0

当'git'不在PATH变量中时,在PS脚本中运行'$ a = git --version'会导致 'git:'git'字样不被识别...' –

+0

运行'git版本“,然后测试'$?'的值。它是“真”或“假”。 – ElpieKay

回答

0

您可以通过查看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 
} 

或者作为一个班轮:

$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') }) 
0

你可以看到命令是否可用:

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

这也恰好覆盖了“git in $ env:path?”这个附加问题。