我想安装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尚未完成安装。

有解决这个问题的好方法吗?

最佳答案

  • Start-Process -Wait开关一起使用,以启动安装程序并等待其完成。
  • 注:正如TToni's answer所指出的那样,用管道输送到| Out-Null就像在您的问题中一样,是使GUI应用程序同步调用的一种不太明显的捷径。
    但是,一般而言,Start-Process使您可以更好地控制调用,例如能够调用隐藏的应用程序。
  • 此外,对于当前 session ,您必须手动将Git安装目录添加到$env:PATH中(因为安装程序对$env:PATH的修改仅对以后的 session 可见),因此仅git的调用就可以成功;以下代码采用标准位置C:\Program Files\Git\cmd;根据需要进行调整-我不清楚/PathOption=CmdTools的功能。
  • 注意:TToni's answer显示了一种不需要预先知道安装目录的替代方法:通过基于更新的注册表定义Git安装目录重新定义$env:PATH。应该添加;唯一的警告是,您可能会消灭$env:PATH的自定义进程内修改,例如在$PROFILE文件中执行的添加。
  • 要使代码更健壮,请通过重试原始测试来添加安装是否成功的检查。
  • $retrying = $false
    do {
      try {
    
        # Test if git can be invoked.
        $null = git --version
        if (-not $retrying) { Write-Host "Git is already installed." }
        break # Git is (now) 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'
    
        # Continue the loop, to see if git is now installed.
        $retrying = $true
      }
    } while ($true)
    
    git clone https://github.com/username/repository
    
    

    关于git - 如果未安装,请安装GIT并克隆,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60525393/

    10-13 08:40
    查看更多