Private/Notifiers/Invoke-NotifierEmail.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
51
52
53
54
55
56
57
58
59
60
function Invoke-NotifierEmail {
    [cmdletbinding()]
    param(
        [parameter(Mandatory, ValueFromPipeline)]
        [ValidateScript({ $_.PSObject.TypeNames[0] -eq 'Watchmen.Notifier.Email' })]
        [pscustomobject]$Notifier,

        [parameter(Mandatory)]
        [ValidateScript({ $_.PSObject.TypeNames[0] -eq 'OperationValidationResult' })]
        [pscustomobject]$Results
    )

    if ($Notifier.Enabled) {
        $o = ($Notifier | Format-Table -Property *  -AutoSize| Out-String)
        Write-Debug -Message "Email notifier called with options:`n$o"


        # If a custom subject line was specified, replace any variables
        if (-not [string]::IsNullOrEmpty($Notifier.Subject)) {
            $Subject = ConvertFrom-PlaceholderString -InputObject $Notifier.Subject -Results $Results

        } else {
            $subject = "($env:COMPUTERNAME) - $($results.Result.ToUpper()) - $($results.RawResult.Name)"
        }

        # If a custom message was specified, replace any variables
        if (-not [string]::IsNullOrEmpty($Notifier.Message)) {
            $msg = ConvertFrom-PlaceholderString -InputObject $Notifier.Message -Results $Results
        } else {
            $msg = @"
Watchmen reported a failure in OVF test:
 
Module: $($results.Module)
File: $($results.FileName)
Describe: $($results.RawResult.Describe)
Context: $($results.RawResult.Context)
Test: $($results.RawResult.Name)
Result: $($results.Result)
Message: $($results.RawResult.FailureMessage)
Duration: $($results.RawResult.Time.ToString())
"@

        }

        $params = @{
            To =  $Notifier.To
            From = $Notifier.FromAddress
            SmtpServer = $Notifier.SmtpServer
            Subject = $subject
            Body = $msg
            UseSSL = $Notifier.UseSSL
            Port = $Notifier.Port
        }
        if ($Notifier.Credential) {
            $params.Credential = $Notifier.Credential
        }

        Send-MailMessage @params
    }
}