带有 csv 文件附件的 Powershell Runbook 电子邮件

Powershell Runbook Email with the csv file attachment

我想从我的 powershell runbook 脚本发送一封电子邮件,我想附加 CSV 文件作为脚本输出,该文件存储在我的 azure 订阅的存储 blob 中。

脚本已准备就绪,我正在收到电子邮件但没有附件。我仍然面临这个问题,当我从 Azure 自动化执行脚本时,作为 runbook,我可以看到以下错误消息。我将所有文件存储在同一个容器中。

新对象:使用“1”个参数调用“.ctor”时出现异常:“找不到文件 'C:\Users\Client\Temp\xxxxxxxx.csv'。”

这是我的输出 --> $ArrayStatus | Export-Csv -NoTypeInformation -Path "$文件名"

$filename 是一个 CSV 文件位置

$ArrayStatus | Export-Csv -NoTypeInformation -Path "$filename"
Get-AzureStorageBlob -Container "xxx" -Blob "$filename" -Context $Context 
Get-AzureStorageBlobContent -force
$attachment = "$filename"

Function Email ($EmailTo, $Body){
$EmailFrom = "xxx"
$Subject = "xxx Alert" 
$SMTPServer = "xxx" 
$SMTPMessage = New-Object 
System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$attach = New-Object System.Net.Mail.Attachment($attachment)
$SMTPMessage.Attachments.Add($attach)
$SMTPMessage.IsBodyHTML = $false
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, xx) 
$SMTPClient.EnableSsl = $true 
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("xx", 
"xx");  
$SMTPClient.Send($SMTPMessage)
            }

我收到电子邮件但没有 CSV 文件附件

前提是您已成功使用 Set-AzureStorageBlobContent 将 export-csv 的输出上传到 Azure blob 存储。您可以使用下面的代码片段从存储容器中读取 blob 并将其存储到本地目标并获取文件的内容并将电子邮件作为附件发送。

# Setting the Azure Storage Context,recommedation is to read sastoken from Runbook assets for security purpose.
$context = New-AzureStorageContext -StorageAccountName "storageaccountname" -SasToken "your storage account sastoken"

# Get the blob contents from storage container and store it local destination . 
Get-AzureStorageBlob -Container "containername" -Blob "filename.csv" -Context $context | Get-AzureStorageBlobContent -force -Destination .

#Get contents of the file
$attachment = Get-Content "filename.csv"

#send an email (provided the smtp server is reachable from where ever you are running this script) 
Send-MailMessage -From 'user@domain.com' -To 'user@domain.com' -Subject 'Content from Blob Storage' -Body "CSV File from Storage blob, sending an attachment for testing" -Attachments .\filename.csv -Priority High -DeliveryNotificationOption OnFailure -SmtpServer 'smtpserver'

希望对您有所帮助。

我没有使用“Blob 上传和下载”过程。但我只是将输出文件保存到本地路径并从那里上传

好的,这就是我所做的:

$OutputFileName = "Test.xlsx"
$asOutput | Export-Excel $OutputFileName -AutoSize -AutoFilter -Append
Send-MailMessage -To $reciever -from $sender -Attachments ".\Test.xlsx" -Subject 'Non-Compliance Report of subscription' -Body "PFA"  -smtpserver smtp.office365.com -usessl -Credential $credemail -Port 587 

我刚刚使用 ".\" 从输出 excel 进入保存文件的本地路径。