1
votes

I'm trying to make a powershell script email stdout & stderr to myself after each run of a windows scheduled task. What I have now is:

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

The variable $allOutput is of type System.Object[], and I need to convert it to a string. How should I do that?

edit: it looks like the first object in $allOutput is a warning from my python script that I'd like to convert to a string: python.exe : C:\Python\lib\site-packages\pymysql\cursors.py:322: Warning: (1264, "Out of range value for column id at row 1") At C:\powershellscript.ps1:1 char:1 + & python.exe script.py 2) ...

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

CategoryInfo : NotSpecified: (C:\Users...pth' at row 1")

:String) [], RemoteException

FullyQualifiedErrorId : NativeCommandError

1
Can you post an example of whats in $allOutput. but you may be able to just use $allOutput.ItemArray[0]Owain Esau
look at the -join operator.Tomalak

1 Answers

2
votes

The immediate fix is to replace
-Body $allOutput | Out-String with
-Body ($allOutput | Out-String)

In order to pass another command's output as an argument to a cmdlet, you must enclose it in (...); in the case of multiple commands, use $(...).

However, use of Out-String will create "noisy" multi-line representations of the stderr output lines from the Python script, so it's better to use -join:

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