Search code examples
powershellazcopy

Result of Powershell Script sent via email


On the result of running the below script, it returns the following:

enter image description here

How could I get this result sent via email? I'm not sure how to get the result into a parameter that I can pass into the Body of an email script:

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/send-mailmessage?view=powershell-6

$azPath = "C:\Program Files (x86)\Microsoft SDKs\Azure\AzCopy\"

Set-Location $azPath

$StorageAccountName = "#"

$StorageAccountKey = "#"

$ContainerName = "#"

$SourceFolder = "#"

$DestURL = "https://$StorageAccountName.blob.core.windows.net/$ContainerName"

$Result = .\AzCopy.exe /source:$SourceFolder /dest:$DestURL /BlobType:block /destkey:$StorageAccountKey /Y /S /XO

$Result

Solution

  • You can either store your result in a file and send it as an attachment:

    $Result | Out-File Result.txt
    Send-MailMessage -From 'User01 <user01@fabrikam.com>' -To 'User02 <user02@fabrikam.com>' -Subject 'Sending the Attachment' -Body "Forgot to send the attachment. Sending now." -Attachments .\Result.txt -SmtpServer 'smtp.fabrikam.com'
    

    Or send the content of $Result (=string[]) as a string in the -Body:

    $body = $Result -join '`n' # Join result to a single string with line breaks
    Send-MailMessage -From 'User01 <user01@fabrikam.com>' -To 'User02 <user02@fabrikam.com>' -Subject 'Sending the Attachment' -Body $body -SmtpServer 'smtp.fabrikam.com'
    

    Or (as stated in @Olfa's comment) convert it to HTML and add the -BodyAsHtml switch:

    $body = $Result | ConvertTo-Html
    Send-MailMessage -From 'User01 <user01@fabrikam.com>' -To 'User02 <user02@fabrikam.com>' -Subject 'Sending the Attachment' -Body $body -SmtpServer 'smtp.fabrikam.com' -BodyAsHtml