powershell email stdout&标准错误

时间:2018-03-08 04:47:43

标签: powershell

我试图制作一个PowerShell脚本邮件stdout&每次运行Windows计划任务后stderr自己。我现在拥有的是:

& python.exe script.py 2>&1 | tee -Variable allOutput
if($allOutput){
  Send-MailMessage -To "<myself@email.com>" `
      -From "Cron Daemon <root@server.com>" `
      -Subject "job output" `
      -Body $allOutput | Out-String `
      -SmtpServer "smtp-relay.server.com"
}

变量$allOutput的类型为System.Object [],我需要将其转换为字符串。我该怎么办?

编辑:看起来$allOutput中的第一个对象是来自我的python脚本的警告,我想转换为字符串: python.exe:C:\ Python \ lib \ site-packages \ pymysql \ cursors.py:322:警告:(1264,&#34;第1行和第34行的列id超出范围值;) 在C:\ powershellscript.ps1:1 char:1 +&amp; python.exe script.py 2)...

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

CategoryInfo:NotSpecified:(C:\ Users ... pth&#39; at row 1&#34;)

:String)[],RemoteException

FullyQualifiedErrorId:NativeCommandError

1 个答案:

答案 0 :(得分:2)

立即修复是替换
-Body $allOutput | Out-String
-Body ($allOutput | Out-String)

为了将另一个命令的输出作为参数传递给cmdlet,您必须将其括在(...);对于多个命令,请使用$(...)

但是,使用Out-String会从Python脚本中创建stderr输出行的“嘈杂”多行表示,因此最好使用-join

-Body ($allOutput -join "`r`n")