如果未安装,请克隆并安装GIT

问题描述 投票:1回答:3

我想安装GIT(如果尚未安装,然后使用PowerShell使用git clone。

我的第一次尝试是这样的:

try {
  git --version | Out-Null
  Write-Host "GIT is already installed."

} catch [System.Management.Automation.CommandNotFoundException]{
  Write-Host "GIT ist not installed."
  Write-Host "Installing..."
  & gitsetup.exe /VERYSILENT /PathOption=CmdTools | Out-Null
}

git clone https://github.com/username/repository

我到git clone时收到command not found错误,因为GIT尚未完成安装。

是否有解决此问题的好方法?

git powershell install
3个回答
2
投票
  • Start-ProcessStart-Process开关一起使用以启动安装程序并等待其完成

    • 注意:正如-Wait所指出的那样,管道传输到TToni's answer就像在您的问题中那样,是使GUI应用程序同步调用的一种模糊的捷径;| Out-Null使您可以更好地控制调用,例如,调用应用程序[[invisible。
  • 此外,您必须将Git安装目录添加到当前会话的Start-Process

    手动

  • 中,这样仅使用$env:PATH的调用就可以成功;以下代码采用标准位置git;根据需要进行调整-我不清楚C:\Program Files\Git\cmd的功能。
      注意:/PathOption=CmdTools显示了一种替代方法,不需要提前知道安装目录:通过基于更新的注册表定义重新定义TToni's answer,即Git安装目录。应该添加;唯一的警告是,您可能会清除$env:PATH的自定义过程中修改,例如在$env:PATH文件中执行的添加。
  • 为了使代码更健壮,请通过重试原始测试来添加安装是否成功的检查。

$PROFILE


1
投票
设置后的$retrying = $false do { try { $null = git --version if (-not $retrying) { Write-Host "GIT is already installed." } break # Git is available, exit. } catch [System.Management.Automation.CommandNotFoundException] { if ($retrying) { Throw "Git is not installed, and installation on demand failed." } Write-Host "GIT ist not installed." Write-Host "Installing..." # Install synchronously (wait for the installer to complete). Start-Process -NoNewWindow -Wait gitsetup.exe '/VERYSILENT /PathOption=CmdTools' # So that invocation by mere file name (`git`) works in this session too, # add the Git installation dir to $env:Path manually. $env:Path += ';C:\Program Files\Git\cmd' # Re-enter the loop to see if git is now installed. $retrying = $true } } while ($true) git clone https://github.com/username/repository 应该已经足以等待进程退出。

但是安装程序可能会修改全局PATH变量以包含git路径,而这在您当前的powershell进程中尚不可见。它仅在流程开始时查找并复制环境。

如果您在设置调用后放置以下行,我希望它能正常工作:

| Out-Null


0
投票
在捕获范围内添加此代码以创建暂停,直到过程结束为止:

$env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User")

© www.soinside.com 2019 - 2024. All rights reserved.