如何以excel格式向powershell发送电子邮件

时间:2017-05-04 14:46:55

标签: powershell

我有一个查询数据库的函数。我希望查询结果通过电子邮件以excel格式发送,无需人工干预。这可能吗?

$Query="SELECT T1.Author,
        T1.Revision,
        T1.Msg AS LogNumber,
        T1.Path as Checkin,
        T2.ThePath as DS_Dependencies
     FROM  Table AS T1
     INNER 
     JOIN Table AS T2
     ON T1.condition = T2.condition"

# redirecting one output stream to the success output stream by using &1
$output = Invoke-Sqlcmd -ServerInstance "sqlInstance" -Database "Database" -Query $Query | Out-String

if ($Output){
    Write-Output "Sending Report"
    $MailUsername = "abc"
    $MailPassword = "xyz"
    $cred = New-Object System.Management.Automation.PSCredential -ArgumentList @($MailUsername,(ConvertTo-SecureString -String $MailPassword -AsPlainText -Force))
    Send-MailMessage -To "youremail@tes.net" -From "test@test.net" -SmtpServer mail.test.net -Credential $cred -Subject "Hey testing:" -Body "$Output"
}

1 个答案:

答案 0 :(得分:0)

使用

$output | Export-CSV

然后通过电子邮件将csv发送给自己。然后,您可以使用导入功能在Excel中加载它:)