2017-08-22 124 views
0

擅長在一封電子郵件中的文件,我有以下SELECT語句從SQL Server數據庫表中提取數據:如何安裝使用PowerShell

$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

我已成功地建立下面的代碼和它的工作對我來說!!!!!!!!!!!!!!:

  $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 = "[email protected]" 
      #$toaddress = "[email protected]" 
      $toaddress = "[email protected]" 
      $bccaddress = "[email protected]" 
      $CCaddress = "[email protected]" 
      $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" } 
0
  • 似乎你的代碼片段不被彼此相關
  • 有沒有嘗試郵寄東西
  • 我建議Datavarable節省$到CSV(XLSX也可以)
  • 該原始示例腳本使用Gmail和潑濺以填充參數

$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 = "[email protected]" 

$Cred = Get-Credential -UserName $emailAcc -Message "Enter gmail password for $emailAcc" 

$MsgParam = @{       
    From = $emailAcc 
    To = "[email protected]" 

    Subject  = $filename 
    Body  = 'blah blah sending $filename' 
    Attachments = $OutPutFile 
    SmtpServer = "smtp.gmail.com" 
}       
Send-MailMessage @MsgParam -UseSSL -cred $Cred