windows - 将 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 的工作示例吗?
解决方案
Bash 可能将$Input
双引号中的双引号扩展为空字符串,因为Input
可能未在 Bash 中定义为变量,因此 PowerShell 获取 command | send_mail.ps1
。解决它的一种方法是使用单引号而不是双引号:
dir | powershell.exe -NoProfile -NonInteractive -Command '$Input | send_mail.ps1'
推荐阅读
- javascript - Mongoose 在错误的键中创建文档:根据模式的值顺序
- doxygen - Doxygen EXCLUDE_PATTERNS 正则表达式
- ruby - 需要基本设置才能使用 ruby appium 框架在真实的 android 设备(chrome 浏览器)上测试网站
- python-2.7 - 使用 Joblib+Dask 将许多子进程生成到 HPC 上的许多不同节点
- html - 内联Content-Security-Policy 是否会影响服务器的策略?
- sql-server - SQL Server:在 CASE 和 ELSE 部分中调用相同的函数
- javascript - 脚本返回“TypeError:无法从 NULL 读取属性长度”,即使它不是
- c++ - 如何在 C++ 应用程序中正确包含标题并使用 STL 向量?
- c# - C# 显示窗口不工作(#32770 (Dialog))
- php - 提交失败后如何保留表单输入