I use a lot of Powershell scripts, many of which are executed by a scheduled task on many different servers. I want to get some feedback from the script so I know it ran correctly, or at least so I can maybe determine when something stopped working correctly.
I’ve begun adding simple email components to the scripts so I can get basic emails sent when the script runs. Here’s the components:
$PSEmailServer = "EmailServerName" #or IP works too
$EmailTo = "email@domain.com"
$EmailFrom = "UserRunningScript@Server.com" #See explanation below
$EmailSubject = "ScriptName successfully run on SeverName"
$EmailBody = "" #Whatever you want there
Send-MailMessage -To $EmailTo -From $EmailFrom -Subject $EmailSubject -Body "$EmailBody but you can add other things here."
In my case, I’m using an on-prem exchange server, so I don’t need the “from” email to be real, and I don’t need any other credentials. So for me, I put the username that runs the scheduled task as the username, and I use the server name as the domain. There’s plenty of ways to do this, but what I like about this over something like “do-not-reply@domain.com” is that I can put email rules to work to sort these messages.
For the Body, other things I like to include are other variables from the script that might change over time. For instance, a common script for me might delete files over a certain age. The script will have a $CutOffDate so I might put that in the body. For instance the body might be:
$EmailBody = "Files were deleted if they were modified before "
And then in the command I might put:
Send-MailMessage -To $EmailTo -From $EmailFrom -Subject $EmailSubject -Body "$EmailBody $CutoffDate"
Something I’d like to do that I haven’t figured out yet is a clean way to list out all items stored in a variable. Again, using the example of a script that deletes old files, I might have a variable of $files that was used to delete all of the files. In the email, I’d think it’d be easy enough to list out those files by just including the variable in the body, but I found it mashes them all together with no spaces or new lines. So I need to figure out a better way to do that.
Speaking of new lines, adding a new line to the body can be an easy way to create a basic table of sorts by just adding the new line character `n to the body.
$EmailBody = "Server:Server1 `nDate:$Date `nPath:C:\Path\Folder"