首页 > 解决方案 > 将 Git Bash 中命令的输出通过管道传输到 Windows 上的 Powershell 脚本

问题描述

我在 git bash 钩子脚本中的 windows 上,想将 git 命令的输出通过管道传输到 powershell 脚本,但无法在 bash 中工作,否则在 windows 命令 shell 中可以工作:

有问题的命令如下:

dir | powershell.exe -NoProfile -NonInteractive -Command "$Input | send_mail.ps1"

这是 send_mail.ps1 的内容:

[CmdletBinding()]
Param
(
[Parameter(ValueFromPipeline)]
[string[]]$Lines
)
BEGIN
{
  $AllLines = ""
}
PROCESS
{
  foreach ($line in $Lines)
  {
    $AllLines += $line
    $AllLines += "`r`n"
  }
}
END
{
  $EmailFrom = "from@sample.com"
  $EmailTo = "to@sample.com"

  $Subject = "Message from GIT"
  $Body = $AllLines

  $SMTPServer = "smtp.sample.com"
  $SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
  $SMTPClient.EnableSsl = $true
  $SMTPClient.Credentials = New-Object System.Net.NetworkCredential("from@sample.com", "asdf1234");
  $SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
}

如果命令是从 powershell 或 windows 命令行运行的,我会成功收到一封包含目录内容的电子邮件。

如果从 bash 运行命令,则会显示以下错误:

In Zeile:1 Zeichen:2
+  | C:\Temp\Test\send_mail.ps1
+  ~
Ein leeres Pipeelement ist nicht zulässig.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : EmptyPipeElement

这大致翻译为“不允许空管道元素”,意味着 $Input 在这里是空的。有人有 bash 的工作示例吗?

标签: windowsbashgitpowershell

解决方案


Bash 可能将$Input双引号中的双引号扩展为空字符串,因为Input可能未在 Bash 中定义为变量,因此 PowerShell 获取 command | send_mail.ps1。解决它的一种方法是使用单引号而不是双引号:

dir | powershell.exe -NoProfile -NonInteractive -Command '$Input | send_mail.ps1'

推荐阅读