PowerShell调用Git进程报错:非Git仓库,需指定仓库路径
解决Git命令执行时"Not a git repository"的问题
这个报错的核心原因很明确:你启动的Git进程没有在目标Git仓库的目录下运行,所以Git无法找到仓库的.git文件夹。下面给你两种简单的解决方法:
方案1:设置Process的工作目录(推荐)
直接在ProcessStartInfo中指定Git仓库的绝对路径作为工作目录,这样Git启动后会自动在这个目录下执行命令。修改你的代码如下:
$repoPath = "C:\Your\Git\Repository\Path" # 替换成你的仓库实际路径 $pinfo = New-Object System.Diagnostics.ProcessStartInfo $pinfo.FileName = "git.exe" $pinfo.RedirectStandardError = $true $pinfo.RedirectStandardOutput = $true $pinfo.UseShellExecute = $false $pinfo.WorkingDirectory = $repoPath # 新增这行,指定仓库目录 $pinfo.Arguments = "commit -m `"{tag}`"" # 也可以简化为`"commit -m `"$tag`""` $p = New-Object System.Diagnostics.Process $p.StartInfo = $pinfo $p.Start() | Out-Null $p.WaitForExit() $stdout = $p.StandardOutput.ReadToEnd() $stderr = $p.StandardError.ReadToEnd() # 修正你之前漏写的$符号 Write-Output "Output: $stdout" Write-Output "Error: $stderr" Write-Output "Error Code: $($p.ExitCode)"
方案2:通过Git的-C参数指定仓库路径
Git本身支持通过-C参数直接指定仓库目录,不需要切换进程工作目录,适合特殊场景下的需求。只需要修改Arguments部分即可:
$repoPath = "C:\Your\Git\Repository\Path" $pinfo.Arguments = "-C `"$repoPath`" commit -m `"{tag}`""
额外小提示
- 你原来的代码里
stderr = $p.StandardError.ReadToEnd()漏了变量前缀$,会导致PowerShell报错,已经在方案1的代码里修正。 - PowerShell里用变量插值(比如
"Output: $stdout")比字符串拼接("Output: " + $stdout)更简洁符合语法习惯。
这样修改后,Git进程就能正确定位到目标仓库,执行commit、pull、push等命令时就不会再出现仓库不存在的错误了。
内容的提问来源于stack exchange,提问作者Wojciech Szabowicz
相关产品推荐
相关产品推荐

