繁体   English   中英

Pipe output from command in Git Bash to Powershell script on windows

[英]Pipe output from command in Git Bash to Powershell script on windows

I am on windows in a git bash hook script and want to pipe output from a git command to a powershell script, but can not get to work in bash what otherwise works in a windows command 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 命令行运行的,我成功接收到 email 与目录的内容。

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

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

这大致翻译为“不允许使用空的 pipe 元素”,这意味着 $Input 此处为空。 有没有人有 bash 的工作示例?

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM