2016-09-27 45 views
1

我想使用PowerShell來運行MySQL腳本並將輸出轉換爲HTML文件或通過電子郵件發送輸出。 但是,我遇到了存儲輸出的變量的問題。變量上的空參數

代碼工作正常,因爲我能夠輸出結果,它只是移動到HTML或電子郵件失敗。

#The dataset must be created before it can be used in the script: 
$dataSet = New-Object System.Data.DataSet 

#MYSQL query 
$command = $myconnection.CreateCommand() 
$command.CommandText = " 
SELECT ID, Date_Close, Time_Close FROM systemcontrol.database_close 
WHERE Date_Close >= CONCAT(YEAR(NOW()), '-', MONTH(NOW()), '-01') 
AND Database_Close_ID = 1 
ORDER BY Date_Close DESC 
"; 

Write-Host "4B - Sales Reports Month End Database" 

$reader = $command.ExecuteReader() 
#The data reader will now contain the results from the database query. 

#Processing the Contents of a Data Reader 
#The contents of a data reader is processes row by row: 
while ($reader.Read()) { 
    #And then field by field: 
    for ($i= 0; $i -lt $reader.FieldCount; $i++) { 
    Write-Output $reader.GetValue($i).ToString() 
    } 
} 

ConvertTo-Html -Body "$reader" -Title "4B - Sales Reports Month End Database" | Out-File C:\************.HTML 

Send-MailMessage -From " Daily Check <[email protected]>" -To "Admin <[email protected]>" -Subject "Daily Check: Server Times" -Body "$reader" -Priority High -Dno onSuccess, onFailure -SmtpServer 1.xx.xx.xx 

$myconnection.Close() 

這是我得到的錯誤:

無法對參數 '身體' 驗證的說法。參數爲空或空。提供一個不爲空或空的參數,然後再次嘗試該命令。

它似乎並不承認$reader變量。我在哪裏錯了?

回答

1

您正在將SqlDataReader對象傳遞給-body參數,該參數預計爲string[]。只需在$result陣列中收集while循環中的值並將其傳遞給機體:

#The dataset must be created before it can be used in the script: 
$dataSet = New-Object System.Data.DataSet 

#MYSQL query 
$command = $myconnection.CreateCommand() 
$command.CommandText = " 
SELECT ID, Date_Close, Time_Close FROM systemcontrol.database_close 
WHERE Date_Close >= CONCAT(YEAR(NOW()), '-', MONTH(NOW()), '-01') 
AND Database_Close_ID = 1 
ORDER BY Date_Close DESC 
"; 

Write-Host "4B - Sales Reports Month End Database" 

$reader = $command.ExecuteReader() 
#The data reader will now contain the results from the database query. 

$result = @() 

#Processing the Contents of a Data Reader 
#The contents of a data reader is processes row by row: 
while ($reader.Read()) { 
    #And then field by field: 
    for ($i= 0; $i -lt $reader.FieldCount; $i++) { 
    $value = $reader.GetValue($i).ToString() 
    Write-Output $value 
    $result += $value 
    } 
} 

ConvertTo-Html -Body $result -Title "4B - Sales Reports Month End Database" | Out-File C:\************.HTML 

Send-MailMessage -From " Daily Check <[email protected]>" -To "Admin <[email protected]>" -Subject "Daily Check: Server Times" -Body "$reader" -Priority High -Dno onSuccess, onFailure -SmtpServer 1.xx.xx.xx 

$myconnection.Close()