Public/Invoke-EmailOnError.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<#
    .SYNOPSIS
    Runs a script block and sends an email if an error occurs.

    .DESCRIPTION
    Used to wrap code that needs to report on configuration or authentication errors. I mean we are forced to change passwords. ;-)

    .INPUTS
    None. You cannot pipe objects to Invoke-EmailOnError.

    .OUTPUTS
    None

    .PARAMETER Script
    A script block to execute with a catch to send email if exception is thrown.

    .PARAMETER Subject
    The subject of the email.

    .EXAMPLE
    PS> Invoke-EmailOnError -Script { Invoke-DoWork } -Subject "Error while executing Invoke-DoWork"

    .LINK
    Set-FileEmailConfig

    .NOTES
    Assumes email config is initialized using Set-FileEmailConfig
#>

function Invoke-EmailOnError {
    param(
        [ScriptBlock]$Script,
        [String]$Subject
    )

    try {
        $perf = Measure-Command { Invoke-Command -ScriptBlock $Script }
        Write-Information "Duration = $($perf.TotalSeconds) seconds"
    } catch {
        Write-Verbose "ERROR Encountered processsing script block: $($_)"
        Write-Verbose "Attempting to email"
        $firstError = $_
        try {
            Send-Email -Subject $Subject -Message "MESSAGE: $($_.ErrorDetails.Message) STACK: $($_.ScriptStackTrace)"
        } catch {
            Write-Information "SENDING EMAIL FAILED: $($_.Exception.Message)"
        } finally {
            throw $firstError
        }
    }
}