发送包含对象的正文的电子邮件

时间:2015-06-15 17:08:04

标签: email powershell foreach

我正在尝试编写一个脚本来搜索AD并查找任何陈旧的计算机,然后向我发送一封电子邮件。但是,有3个要求:

  1. 获取任何超过90天的电脑的lastlogondate
  2. 一旦我得到该列表,我就进行ping测试
  3. 从ping测试中,我接受了并且最后一次设置了密码
  4. Import-Module activedirectory
    #Date = today's date -90 days
    $date=[datetime]::Today.adddays(-90)
    $pcArray = @()
    $bodyArray=@()
    $passArray=@()
    $oldpc = Get-ADComputer -properties * -Filter 'lastlogondate -le $date' |
             where {$_.name -like '*WD*'} |select name, lastlogondate
    
    foreach ($pc in $oldpc)
    {
        if (!(Test-Connection $pc.name -quiet)) 
        {
            $script:pcArray += $pc.name      
        }
    }
    foreach ($failping in $pcArray)
    {
        $lastpass = Get-ADComputer $failping -properties * |
                    select name, passwordlastset
        $script:passArray += $lastpass
    }
    
    #Send email
    foreach ($badpc in $oldpc)
    {
        $script:bodyArray += $badpc
    }
    if($bodyArray) 
    {
        Send-MailMessage -to "toEmailaddress "-Subject "Stale Computers Check" -From "fromEmailaddress "-SmtpServer "smtpserver" -BodyAsHtml "The following computers have not been logged into for over 90 days </br>$bodyArray </br></br>
        The following computers are not pingable</br>$pcArray </br></br>The last password changed on those pcs are </br>$lastpass"
    }
    

    我收到的电子邮件如下:

    The following computers have not been logged into for over 90 days 
    
    
    The following computers are not pingable
    pcname1 pcname2 
    
    The last password changed on those pcs are 
    @{name=pcname1; passwordlastset=12/08/2014 14:59:38} 
    

    正如您所看到的,在运行脚本后,$bodyArray变量尚未发送,在PowerShell中,我调用了$bodyArray,并得到以下输出:

    name       lastlogondate
    ----       -------------
    pcname1    9/13/2014 8:06:21 PM
    pcname2    9/17/2014 5:25:25 PM
    pcname3    12/5/2014 11:16:16 AM
    pcname4    12/8/2014 3:00:01 PM
    

    我已经尝试了ToString()并正如您在上面看到的那样进行迭代。

    对于数字2,我想在换行符中获取每个PC名称。我尝试加入+ `n,但这不起作用。

    对于3号,我只能输出1台PC而不是整个阵列。通过pscmd运行我也得到1台PC,但是因为我在$pcArray中循环使用2台PC,所以应该有2台。

1 个答案:

答案 0 :(得分:1)

此外,如果你希望它看起来更漂亮和可读,你可以做这样的事情,将它吐出一个表:

$body += "<body><table width=""560"" border=""1""><tr>"
$bodyArray[0] | ForEach-Object {
foreach ($property in $_.PSObject.Properties){$body += "<td>$($property.name)</td>"}
} 
$body += "</tr><tr>"
$bodyArray | ForEach-Object {
foreach ($property in $_.PSObject.Properties){$body += "<td>$($property.value)</td>"}
$body += "</tr><tr>"
}
$body += "</tr></table></body>"

$bodyArray[0] | ForEach-Object将列名打印为表头。并且$bodyArray | ForEach-Object打印出表中的所有值。如果你想获得幻想,你甚至可以添加一些CSS来使表格看起来更好