当将结果存储在变量中发送给所有结果显示在第一行中时通过电子邮件发送

问题描述 投票:0回答:1

[当我在powershell中看到结果时,它是相当不错的,但是发送到电子邮件中后,$ list中的所有结果都显示在1行中。我的代码有问题吗?

$servers = "serveraddress"
$recipients = "[email protected]" 

foreach ($server in $servers){
    Write-Output $server
    $list = Invoke-command -computer $server {$profiles = Get-ChildItem -Recurse -path c:\TestFolder aaa.xml; 
    foreach ($p in $profiles){
        $p.fullname
    }
    }

}
$list
if ($list -ne $null){
    Send-MailMessage -From [email protected] -To $recipients -Subject "Something Wrong" -Body “Server: $($server)`nLocations:`n$list`n” -SmtpServer smtp.abc.com
}
else
{
    #do nothing
}

当前结果将像这样显示,我想在新行中的位置下面放置所有行。

Server: serveraddress
Locations:
c:\TestFolder\AAA\aaa.xml c:\TestFolder\bbb\aaa.xml
powershell
1个回答
0
投票

如果我正确理解了这个问题,我建议做这样的事情:

$servers    = "serveraddress"
$recipients = "[email protected]" 

$list = foreach ($server in $servers) {
    $files = Invoke-Command -ComputerName $server {(Get-ChildItem -Path 'c:\TestFolder' -Filter '*.xml' -File -Recurse).FullName}
    # next join everything with newlines to output a block of text that gets collected in array variable $list
    "Server: $server{0}Locations:{0}{1}{0}" -f [Environment]::NewLine, ($files -join [Environment]::NewLine)
}


if ($list) {
    # show on screen
    $list

    # create a hashtable with parameters for Send-MailMessage
    $mailParams = @{
        From       = '[email protected]'
        To         = $recipients
        Subject    = 'Something Wrong'
        Body       = $list -join [Environment]::NewLine
        SmtpServer = 'smtp.abc.com'
    }
    # send the email
    Send-MailMessage @mailParams
}
else {
    #do nothing
}

注意我正在使用Splatting cmdlet上的Send-MailMessage。这样做会创建易于维护的代码。

© www.soinside.com 2019 - 2024. All rights reserved.