Last active
September 13, 2018 20:54
-
-
Save tygerbytes/fb009df2bbb7b585c96f3916849f1834 to your computer and use it in GitHub Desktop.
Out-Email: PowerShell function/cmdlet that tees output stream to an email
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Out-Email (github.com/tygerbytes) | |
# | |
# Example: | |
# Process-LotsOfWork | Out-Email -To bob@example.com, tina@example.com -Subject "Lots of work" | |
# Sends an email to Bob and Tina with the output of the function, Process-LotsOfWork. | |
# | |
# Example (Redirect all streams to standard output so that errors will appear in email): | |
# Process-LotsOfWork *>&1 | Out-Email [...] | |
# | |
# Example (Continue processing output after piping to Out-Email): | |
# Process-LotsOfWork *>&1 | Out-Email [...] -PassThru | Select [...] | |
# | |
function Out-Email { | |
[CmdletBinding()] | |
Param ( | |
[Parameter(Mandatory = $true)][string[]]$To, | |
[Parameter(Mandatory = $true)][string]$Subject, | |
[Parameter(Mandatory = $false)][Switch]$PassThru, | |
[Parameter(ValueFromPipeline = $true)][string[]]$inputs, | |
[string]$TempOutputPath = "$($env:TEMP)\EmailOutput-$([guid]::NewGuid()).txt" | |
) | |
begin { | |
if (!($PSEmailServer)) { | |
Write-Error "`$PSEmailServer is not set. I don't know where your email server is." | |
} | |
Write-Host "[Out-Email] Saving output to $TempOutputPath" -ForegroundColor DarkBlue | |
New-Item -Type File $TempOutputPath | Out-Null | |
} | |
process { | |
foreach ($input in $inputs) { | |
$input | Out-File -FilePath $TempOutputPath -Append | |
if ($PassThru) { | |
Write-Output $input | |
} | |
} | |
} | |
end { | |
Write-Host "Sending emails to $($To -join ',')" -ForegroundColor DarkBlue | |
$body = "" | |
foreach($line in $(Get-Content $TempOutputPath)) { | |
$body += "$line`n" | |
} | |
$mailparms = @{ | |
'To' = $To -join ';'; | |
'Subject' = $Subject; | |
'From' = "$($env:USERNAME)@$($env:USERDNSDOMAIN)"; | |
'Body' = $body; | |
'BodyAsHtml' = $false; | |
'SmtpServer' = $PSEmailServer; | |
} | |
Remove-Item -Path $TempOutputPath | |
Send-MailMessage @mailparms | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment