0

现在我的目标是从 url 下载包含威胁数据的 CSV,捕获两列文件名和设备名,它们都是 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
4

3 回答 3

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 
于 2017-12-06T22:07:16.907 回答
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
于 2020-11-29T18:09:12.780 回答
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
于 2017-12-06T17:17:38.310 回答