gpt4 book ai didi

windows - 运行带有 Git 命令的远程 PowerShell 脚本会导致 NativeCommandError

转载 作者:可可西里 更新时间:2023-11-01 12:43:17 61 4
gpt4 key购买 nike

我在执行远程 PowerShell 脚本时遇到错误。在我的本地机器上,我正在运行一个 PowerShell 脚本,该脚本使用 Invoke-Commandcd 放入远程 Amazon Windows Server 实例上的一个目录中,随后使用 Invoke-命令 执行驻留在该服务器实例上的脚本。服务器上的脚本正在尝试从 GitHub 克隆一个存储库。我可以在服务器脚本中成功执行“ls”甚至“git --version”之类的操作。但是 git clone, git pull 等会导致如下错误:

Cloning into 'MyRepo'... + CategoryInfo : NotSpecified: (Cloning into 'MyRepo'...:String) [], RemoteException + FullyQualifiedErrorId : NativeCommandError

这是我第一次使用 PowerShell 或 Windows Server。谁能就这个问题提供一些指导。

客户端脚本:

$s = new-pssession -computername $server -credential $user
invoke-command -session $s -scriptblock { cd C:\Repos; ls }
invoke-command -session $s -scriptblock { param ($repo, $branch) & '.\clone.ps1' -repository $repo -branch $branch} -ArgumentList $repository, $branch
exit-pssession

服务器脚本:

param([string]$repository = "repository", [string]$branch = "branch")
git --version
start-process -FilePath git -ArgumentList ("clone", "-b $branch https://github.com/MyGithub/$repository.git") -Wait

我已将服务器脚本更改为使用启动进程,它不再抛出异常。它创建新的存储库目录和 .git 目录,但不写入 github 存储库中的任何文件。这闻起来像权限问题。再次手动调用脚本(远程桌面进入 amazon box 并从 powershell 执行)就像一个魅力。

最佳答案

无论何时您从 PowerShell 调用外部可执行文件,我都强烈建议您使用 Start-Process。与直接调用可执行文件相比,Start-Process cmdlet 可以更好地处理命令行参数。

重要:您还必须知道,如果您运行两个单独的 Invoke-Command 命令(除非您使用的是 -Session参数),您将在两个完全不同的 PowerShell 远程处理 session 中操作!如果您使用 cd(也就是 Set-Location 的别名)命令,当您运行 Git 命令。

$GitExe = '{0}\path\to\git.exe' -f $env:SystemDrive;
$ArgumentList = 'clone "c:\path\with spaces\in it"';
Start-Process -FilePath $GitExe -ArgumentList $ArgumentList -Wait -NoNewWindow;

Start-Process cmdlet 上还有一个-WorkingDirectory 参数,允许您为进程指定工作目录。与其使用 Set-Location cmdlet 设置 PowerShell session 的“当前目录”,不如为进程指定工作目录的完整路径可能更好。例如,假设您在 c:\repos\repo01 中有一个 Git 存储库,而您的 Git exe 位于 c:\git 中。您不必太担心 PowerShell 的“当前目录”在哪里,而应该专注于指定完整路径:

  1. Git 可执行文件
  2. Git 存储库

这是一个如何实现的例子:

Start-Process -FilePath c:\git\git.exe -ArgumentList 'clone "c:\repos\repo01" "c:\repos\repo02"" -Wait -NoNewWindow;

注意:我不知道 Git 命令,但你应该能够调整上面的 $ArgumentList 变量的值,让它为你工作.在 PowerShell 中,您可以将双引号放在单引号内,而不必担心转义它们。

关于windows - 运行带有 Git 命令的远程 PowerShell 脚本会导致 NativeCommandError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21002919/

61 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com