Powershell - 将CSV数据发送到表格中的电子邮件

时间:2017-12-06 17:01:46

标签: powershell csv email import-csv

现在我的目标是从网址下载包含威胁数据的CSV,捕获两列,文件名和DeviceName,这两列都是CSV中的标题。然后,我想将这些数据导出到电子邮件中的一行,然后由我们的安全团队中的两名成员以明文格式进行审核。目标是让他们不必直接从CSV下载和复制粘贴,因为CSV中存在大量无关数据。

这是一个非常简单的脚本,所以一切正常。我的问题是:如何从csv中提取两列数据并将其写入电子邮件正文?理想情况下,在某种表中,两列是对齐的。

我在网上找到了一些资源,最明显的是从PowerShell界面获取任何对象的脚本,将对象(表格)转换为HTML,然后通过电子邮件发送:https://gallery.technet.microsoft.com/scriptcenter/bd0c8d87-466f-4488-92a2-0f726cb6f4cd

这是完美的,因为这正是我想要做的。我只是不确定如何正确地将数据从CSV传递到powershell函数。

请注意,这也是我在powershell中的第一个项目,它主要是通过technet文档和我在网上找到的代码示例碎片拼凑而成的。我是一名初级系统管理员,所以没有大量的编程背景。

谢谢束!

更新1

这次设法取得了一些成功,但不幸的是,通过电子邮件发送的输出是一个乱码列表,与CSV中的任何数据都不对应。

我很确定我的错误就在这里,但我不确定我在哪里失败:

$csv = Import-Csv $output | Select "File Name",DeviceName | ConvertTo-Html

我的其余代码如下:

<#
.SYNOPSIS
Send an email with an object in a pretty table
.DESCRIPTION
Send email
.PARAMETER InputObject
Any PSOBJECT or other Table
.PARAMETER Subject
The Subject of the email
.PARAMETER To
The To field is who receives the email
.PARAMETER From
The From address of the email
.PARAMETER CSS
This is the Cascading Style Sheet that will be used to Style the table
.PARAMETER SmtpServer
The SMTP relay server
.EXAMPLE
PS C:\> Send-HtmlEmail -InputObject (Get-process *vmware* | select CPU, WS) -Subject "This is a process report"
An example to send some process information to email recipient
.NOTES
NAME        :  Send-HtmlEmail
VERSION     :  1.1.0   
LAST UPDATED:  01/03/2013
AUTHOR      :  Milo
.INPUTS
None
.OUTPUTS
None
#> 

function Send-HTMLEmail {
#Requires -Version 2.0
[CmdletBinding()]
 Param 
   ([Parameter(Mandatory=$True,
               Position = 0,
               ValueFromPipeline=$true,
               ValueFromPipelineByPropertyName=$true,
               HelpMessage="Please enter the Inputobject")]
    $InputObject,
    [Parameter(Mandatory=$True,
               Position = 1,
               ValueFromPipeline=$true,
               ValueFromPipelineByPropertyName=$true,
               HelpMessage="Please enter the Subject")]
    [String]$Subject,    
    [Parameter(Mandatory=$False,
               Position = 2,
               HelpMessage="Please enter the To address")]    
    [String[]]$To = "smurphy@klick.com",
    [String]$From = "cylancereporting@klick.com",    
    [String]$CSS,
    [String]$SmtpServer ="smtp.klick.com"
   )#End Param

if (!$CSS)
{
    $CSS = @"
        <style type="text/css">
            table {
            font-family: Verdana;
            border-style: dashed;
            border-width: 1px;
            border-color: #FF6600;
            padding: 5px;
            background-color: #FFFFCC;
            table-layout: auto;
            text-align: center;
            font-size: 8pt;
            }

            table th {
            border-bottom-style: solid;
            border-bottom-width: 1px;
            font: bold
            }
            table td {
            border-top-style: solid;
            border-top-width: 1px;
            }
            .style1 {
            font-family: Courier New, Courier, monospace;
            font-weight:bold;
            font-size:small;
            }
            </style>
"@
}#End if

$HTMLDetails = @{
    Title = $Subject
    Head = $CSS
    }

$Splat = @{
    To         =$To
    Body       ="$($InputObject | ConvertTo-Html @HTMLDetails)"
    Subject    =$Subject
    SmtpServer =$SmtpServer
    From       =$From
    BodyAsHtml =$True
    }
    Send-MailMessage @Splat

}#Send-HTMLEmail


#Defines variables
$url = "https://protect.cylance.com/Reports/ThreatDataReportV1/threats/BE5ABB1717DB46978BED0AF14A308557"
$output = "$PWD\ThreatsDataReport.csv"

(New-Object System.Net.WebClient).DownloadFile($url, $output)
#Downloads the CSV from $url and saves it to $output

$csv = Import-Csv $output | Select "File Name",DeviceName | ConvertTo-Html

Send-HTMLEmail -InputObject ($csv) -Subject "Cylance: Weekly Summary"

原始代码

$url = "foo.com/directlinktocsv"
$output = "$PSScriptRoot\ThreatsDataReport.csv"
$emailSMTPServer = "smtp.mydomain.com"
$emailFrom = "myemail@mydomain.com"
$emailRecipients = @("Foo <foo@mydomain.com>", "Bar <bar@mydomain.com>")
$emailSubject = "Cylance Detected Threats"
$emailBody = "This is where I want my output to go"

(New-Object System.Net.WebClient).DownloadFile($url, $output)

$csv = Import-Csv $output 

    $csv."File Name" | ForEach-Object {
    $_


    }

    $csv.DeviceName | ForEach-Object {

    $_

    }


Send-MailMessage -From $emailFrom -To $emailRecipients -SmtpServer $emailSMTPServer -subject $emailSubject -Body $emailBody

3 个答案:

答案 0 :(得分:1)

管理得出答案!

首先,我在链接中抛弃了Send-HTMLEmail,因为它既不必要也不特别有用。

我的固定工作代码是

#Defines variables
$url = "mysite.com/ThreatsDataReport.csv"
$output = "$PWD\ThreatsDataReport.csv"
$emailSMTPServer = "smtp.mydomain.com"
$emailFrom = "reportingemail@domain.com"
$emailRecipients = @("Foo <foo@domain.com>"), "Bar <bar@domain.com>")
$emailSubject = "Cylance Reporting"

(New-Object System.Net.WebClient).DownloadFile($url, $output)
#Downloads the CSV from $url and saves it to $output

#Sets HTML Head Information
$a = "<style>"
$a = $a + "BODY{background-color:peachpuff;}"
$a = $a + "TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}"
$a = $a + "TH{border-width: 1px;padding: 0px;border-style: solid;border-color: black;background-color:thistle}"
$a = $a + "TD{border-width: 1px;padding: 0px;border-style: solid;border-color: black;background-color:palegoldenrod}"
$a = $a + "</style>"




$csv = Import-Csv $output | Select "File Name",DeviceName,"File Path" | ConvertTo-Html -head $a -Body "<H2>Cylance Weekly Report</H2>"
#Imports the CSV saved to $output.
#Selects File Name, Device Name, and File Path columns, then converts to HTML using the Head +Body Information
$emailBody = "$csv"

#defines the body text of the email. Note that this has to be a string, $emailBody = $csv will not work on its own. 

Send-MailMessage -From $emailFrom -To $emailRecipients -SmtpServer $emailSMTPServer -subject $emailSubject -Body $emailBody -BodyAsHtml
#Sends the actual email 

答案 1 :(得分:1)

感谢您发布此信息。我将其用作模板,并扩展了一些我想要的东西。我的csv数据来自PRTG。

我可以使用Invoke-WebRequest来下载csv。插入-UseBasicParsing允许使用任务计划程序计划脚本。

$WebResponse = Invoke-WebRequest -UseBasicParsing "URL to CSV DATA"
$output = $WebResponse.Content

我还为内容添加了一些过滤和排序逻辑

#Uses data from WebResponse, filters, sorts, and selects columns
#Multiple sections of the resultant html output allows for formatting
#Evaulates results set and sets alternate header when null
#Sets results and converts to html while inserting HTML head
$prep1 = ConvertFrom-Csv $output | ? Status -like Down | sort -Property 'Device', 'Sensor'| Select Probe,Device,Sensor
if (!$prep1) { $out1 = '<H3>No Sensors in <span style="color: #ff0000;">Down</span> State</H3>' }
else {$out1 = $prep1 | ConvertTo-Html -head $head -Body '<H3>Sensors in <span style="color: #ff0000;">Down</span> State</H3>'}

当我想要具有不同标题的数据的不同部分时,我重复了上面的内容,然后通过将所有内容附加在一起来完成它。

#Create HTML Body
$emailBody = "$out1 $out2"

这是完成的脚本。

#Define variables
$WebResponse = Invoke-WebRequest -UseBasicParsing "URL with output=csvtable"
$output = $WebResponse.Content
$emailSMTPServer = "smtp.mydomain.com"
$emailFrom = "reportingemail@domain.com"
$emailRecipients = @("Foo <foo@domain.com>"), "Bar <bar@domain.com>")
$emailSubject = "PRTG Status Report"

#Sets HTML Head Information when result set is not Null
$head = "<style>"
$head = $head + "BODY{}"
$head = $head + "TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}"
$head = $head + "TH{border-width: 1px;padding: 1px;border-style: solid;border-color: black;background-color:gainsboro}"
$head = $head + "TD{border-width: 1px;padding: 1px;border-style: solid;border-color: black;background-color:palegoldenrod}"
$head = $head + "</style>"

#Uses data from WebResponse, filters, sorts, and selects columns
#Multiple sections of the resultant html output allows for formatting
#Evaulates results set and sets alternate header when null
#Sets results and converts to html while inserting HTML head

$prep1 = ConvertFrom-Csv $output | ? Status -like Down | sort -Property 'Device', 'Sensor'| Select Probe,Device,Sensor
if (!$prep1) { $out1 = '<H3>No Sensors in <span style="color: #ff0000;">Down</span> State</H3>' }
else {$out1 = $prep1 | ConvertTo-Html -head $head -Body '<H3>Sensors in <span style="color: #ff0000;">Down</span> State</H3>'}

$prep2 = ConvertFrom-Csv $output | ? Status -like Warning | ? Sensor -Notmatch 'Windows Updates Status' |sort -Property 'Device', 'Sensor'| Select Probe,Device,Sensor
if (!$prep2) { $out2 = '<H3>No Sensors in <span style="color: #ffcc00;">Warning</span> State</H3>' }
else {$out2 = $prep2 | ConvertTo-Html -head $head -Body '<H3>Sensors in <span style="color: #ffcc00;">Warning</span> State</H3>'}

#Create HTML Body
$emailBody = "$out1 $out2"

#Send email 
Send-MailMessage -From $emailFrom -To $emailRecipients -SmtpServer $emailSMTPServer -subject $emailSubject -Body $emailBody -BodyAsHtml

答案 2 :(得分:0)

如果您只希望CSV文件中的第一行包含这些列名,您可以执行以下操作:

$csv = Import-Csv $output | Select-Object -First 1
$emailBody = "File Name: {0}`r`nDevice Name: {1}" -f
  $csv."File Name", $csv.DeviceName
$params = @{
  "From"       = $emailFrom
  "To"         = $emailRecipients
  "SmtpServer" = $emailSMTPServer
  "Subject"    = $emailSubject
  "Body"       = $emailBody
}
Send-MailMessage @params

要获取多行输出,您可以执行以下操作:

$emailBody = Import-Csv $output |
  Select-Object "File Name",DeviceName |
  Format-Table -AutoSize | Out-String
$params = @{
  "From"       = $emailFrom
  "To"         = $emailRecipients
  "SmtpServer" = $emailSMTPServer
  "Subject"    = $emailSubject
  "Body"       = $emailBody
}
Send-MailMessage @params