【问题标题】:Get git result from commad using powershell and pipeline in c#在 c# 中使用 powershell 和管道从命令中获取 git 结果
【发布时间】:2018-01-17 11:52:38
【问题描述】:

您好,我正在尝试使用 power shell 和 c# 作为管理工具创建某种混合,因此 powershell 中的简单脚本可以检查 repo 状态

$git_status = git status
Write-Output $git_status

现在使用管道并运行

using (Runspace runspace = RunspaceFactory.CreateRunspace())
{
        runspace.Open();
        Pipeline pipeline = runspace.CreatePipeline();
        pipeline.Commands.AddScript(powershellScript);
        pipeline.Commands.Add("Out-String");
        Collection<PSObject> results = pipeline.Invoke();
        runspace.Close();

        StringBuilder output = new StringBuilder();
        foreach (PSObject obj in results)
        {
            output.AppendLine(obj.ToString());
        }

        return output.ToString();
}

但是我得到空结果,当我在 IDE power shell 中运行脚本时,结果如下所示:

写主机“$git_status” 在分支 master 你的分支是最新的'origin/master'。要提交的更改: (使用“git reset HEAD ...”取消暂存)修改:DeviceDatabase/Platforms.xml

我能做些什么来让这个响应返回到 c# 过程?

【问题讨论】:

  • 据我了解,powershell 和 git 并不能很好地配合使用。 PS 操作记录,git 输出原始字节流。既然你无论如何都要写代码,你可能最好只阅读 gits 输出,然后用 C# 处理它

标签: c# git powershell


【解决方案1】:

Write-Host 只会将输出打印到终端,但不会将其传递到标准输出。如果你想得到输出 - 使用Write-Output

Write-Host 用于构建 UX:更改输出文本颜色等。如果您希望将脚本作为工具组合起来解决更大的问题,请使用 Write-Output

你可以找到更好的解释here。我将使用链接中的示例代码来扩展一点:

function Receive-Output 
{
    process
    {
        # catch input from pipe and print it in green
        Write-Host $_ -ForegroundColor Green
    }
}

# this will print green text, because it was passed to Receive-Output
Write-Output "this is a test" | Receive-Output

# this will print white text, because it was not passed to Receive-Output
# there's a good chance "this is a test" will already be printed by the time Receive-Output gets called
Write-Host "this is a test" | Receive-Output

编辑:git status 打印出彩色文本时,我们可以放心地假设它在PowerShell 中使用Write-Host。根据Posh-Git reads git status into an object 的方式,我编译了一个小示例代码,应该可以解决您的问题:

> $status = (git -c color.status=false status)
> Write-Output $status

这是我得到的输出(Windows 10,PowerShell Core 6.0):

【讨论】:

  • 我已经改变了这一点,我认为问题出在其他地方,因为 Git 是由 power shell 脚本启动的单独进程,它的输出仅显示为不包含在 power shell 中,我认为它应该被转储到某种形式的 var 和输出的,但这只是我需要检查的理论。
  • @WojciechSzabowicz ,请查看更新的答案是否有帮助。
猜你喜欢
  • 2019-07-16
  • 2012-05-10
  • 2010-09-18
  • 1970-01-01
  • 1970-01-01
  • 2017-05-03
  • 1970-01-01
  • 1970-01-01
  • 2013-02-13
相关资源
最近更新 更多