powershell - Best practice for emailing a body of appended strings? -
i have powershell script automates process , emails report of happened.
send-mailmessage -to $toaddress -from "no-reply@domain.org" -subject "automation status" -body $bodystr -smtpserver server1 -ea stop
so $bodystr
appended string throughout script report happened , has multiple lines. things like:
$bodystr = $bodystr + "line found: 305`n" $bodystr = $bodystr + "moving line 305 574`n"
the send-mailmessage
command @ bottom of script outside function. other code in various different functions.
the issue $bodystr
not seem accessible inside functions, , email lacking lot of information.
i believe use set-variable
or passing arguments, there many arguments seems farther away best practice add new argument each function keep string updated.
what's best practice handle this?
as general rule, don't write data variables outside scope of function.
if compiling email gathering data multiple sources, abstract away in multiple functions 1 thing each , have them return multiline string relevant output.
at end of script, collect different message body parts , join them single string before sending.
in example, have script takes path log file, defines function extract errors log file, , send email errors in body:
param( [validatescript({test-path $_ -pathtype leaf })] [string]$logpath = 'c:\path\to\file.log', [string]$from = 'noreply@company.example', [string]$to = @('ceo@company.example','finance@company.example'), [string]$subject = 'super important weekly report', [string]$smtpserver = $psemailserver, [string]$credential ) # define functions straight forward purpose # e.g. searching logfile errors function parse-logfile { param($logpath) [string[]]$logerrors = @() get-content $logpath |foreach-object{ if($_ -contains $error){ $logerrors += $_ } } # create , return custom object has error details properties new-object psobject -property @{ errorcount = $logerrors.count errors = $logerrors } } # create email template that's easy maintain # store in file , add $templatefile parameter script ;-) $emailtemplate = @' hi there! found {0} errors in log file: {1} {2} regards zeno '@ # use function(s) create , gather details need $errorreport = parse-logfile -logpath $logpath # if necessary, concatenate strings -join $errorstring = $errorreport.errors -join "`n" # use format operator final body string $body = $emailtemplate -f $errorreport.errorcount, $logpath, $errorstring # set splatting table (get-help about_splatting) $mailparams = @{ = $to = $from subject = $subject body = $body smtpserver = $smtpserver } if($psboundparameters.containskey('credential')){ $mailparams['credential'] = $credential } # send mail send-mailmessage @mailparams
Comments
Post a Comment