我有以下select语句从SQL Server数据库表中提取数据:
$QUERY = "SELECT * FROM Table1"
$DataVariable = Invoke-Sqlcmd -ServerInstance "MyInstance" -Database "MyDB" -Query $QUERY
如何将$ DataVariable作为excel文件附加到我的电子邮件中?
我正在处理以下代码:
$Date = get-date -format "dd-MMM-yyyy"
$Day = $Date.DayOfWeek
$DateTested = $Date
$filename = "MYReport_$(get-date -f yyyy-MM-dd).XLS"
$OutputFile = "\\server\c$\Output\$filename"
我似乎没有去任何地方。有人可以帮忙吗?
由于
答案 0 :(得分:0)
$QUERY = "SELECT * FROM Table1"
$DataVariable = Invoke-Sqlcmd -ServerInstance "MyInstance" -Database "MyDB" -Query $QUERY
$filename = "MYReport_$(get-date -f yyyy-MM-dd).csv"
$OutputFile = "\\server\c$\Output\$filename"
$DataVariable | Export-Csv $OutPutFile -NoTypeInformation
$emailAcc = "youraccount@gmail.com"
$Cred = Get-Credential -UserName $emailAcc -Message "Enter gmail password for $emailAcc"
$MsgParam = @{
From = $emailAcc
To = "recipient@domain.com"
Subject = $filename
Body = 'blah blah sending $filename'
Attachments = $OutPutFile
SmtpServer = "smtp.gmail.com"
}
Send-MailMessage @MsgParam -UseSSL -cred $Cred
答案 1 :(得分:0)
我已设法构建下面的代码,它对我有用!!!!!!!!!!!!!!:
$DataVariable = Invoke-Sqlcmd -ServerInstance $ResultsInstance -Database $ResultsDatabase -Query $SQL
$Date = get-date -format "dd-MMM-yyyy"
$Day = $Date.DayOfWeek
$DateTested = $Date
$filename = "MyReport_$(get-date -f yyyy-MM-dd).csv"
$OutputFile = "\\serverName\c$\Output\$filename"
$DataVariable | Export-csv $OutPutFile -NoTypeInformation
$to = "Support"
$body = "Dear <b><font color=black>$to</b></font> <br>"
$body += "<p>Please find attached report.</p> <br>"
$body += "Kind Regards<br>"
$body += "Dev Team <br>"
$fromaddress = "xyz@xyz.com"
#$toaddress = "x@ytm.com"
$toaddress = "x@ytm.com"
$bccaddress = "x@ytm.com"
$CCaddress = "x@ytm.com"
$Subject = "My weekly report"
$attachment = $OutputFile
$smtpserver = "xyzmail"
####################################
$message = new-object System.Net.Mail.MailMessage
$message.From = $fromaddress
$message.To.Add($toaddress)
$message.CC.Add($CCaddress)
$message.Bcc.Add($bccaddress)
$message.IsBodyHtml = $True
$message.Subject = $Subject
$attach = new-object Net.Mail.Attachment($attachment)
$message.Attachments.Add($attach)
$message.body = $body
$message.Priority = [System.Net.Mail.MailPriority]::High
$smtp = new-object Net.Mail.SmtpClient($smtpserver)
if ($DataVariable) {
$smtp.Send($message)
Write-Host "The variable is not null" }