2012-06-29 30 views
6

Ok, esto puede haber sido respondido, pero soy nuevo y trato de aprender, así que supongo que no lo estoy "entendiendo". Tengo una variable que contiene una tabla de información (la obtuve de una consulta SQL). Puedo mostrar la variable en la pantalla y ver la tabla, pero cuando intento crear un correo electrónico HTML con ella en el cuerpo, se confunde.Tabla de visualización de PowerShell En HTML Correo electrónico

Aquí está el código:

# This code sets up the HTML table in a more friendly format 
$style = "<style>BODY{font-family: Arial; font-size: 10pt;}" 
$style = $style + "TABLE{border: 1px solid black; border-collapse: collapse;}" 
$style = $style + "TH{border: 1px solid black; background: #dddddd; padding: 5px; }" 
$style = $style + "TD{border: 1px solid black; padding: 5px; }" 
$style = $style + "</style>" 

# This code defines the search string in the IssueTrak database tables 
$SQLServer = "Blah" 
$SQLDBName = "Blah" 
$SQLUsername = "Blah" 
$SQLPassword = "Blah" 
$SQLQuery = "SELECT u.FirstName,u.LastName,u.EMail,COUNT(UserID) as Count 
     FROM dbo.Issues i with(nolock) 
     JOIN DBO.Users u with(nolock) on u.UserID = i.NextActionBy 
     where i.Status='Open' 
     group by u.FirstName,u.LastName,u.EMail 
     order by Count(*) desc" 

# This code connects to the SQL server and retrieves the data 
$SQLConnection = New-Object System.Data.SqlClient.SqlConnection 
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; uid = $SQLUsername; pwd = $SQLPassword" 

$SqlCmd = New-Object System.Data.SqlClient.SqlCommand 
$SqlCmd.CommandText = $SqlQuery 
$SqlCmd.Connection = $SqlConnection 

$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter 
$SqlAdapter.SelectCommand = $SqlCmd 

$DataSet = New-Object System.Data.DataSet 
$SqlAdapter.Fill($DataSet) 
$SqlConnection.Close() 

# This code outputs the retrieved data 
$DataSet.Tables | Format-Table -Auto 

# This code emails a report regarding the results of the retrieved data 
$smtpServer = "Blah" 
$smtpFrom = "Blah" 
$smtpTo = "Blah" 
$messageSubject = "IssueTrak Open Issues By Next Action Report" 
$message = New-Object System.Net.Mail.MailMessage $smtpfrom, $smtpto 
$message.Subject = $messageSubject 
$message.IsBodyHTML = $true 
$message.Body = "Here is a listing of open issues in IssueTrak, sorted by Next Action.<br><br>" 
$message.Body = $message.Body + $html 

$smtp = New-Object Net.Mail.SmtpClient($smtpServer) 
$smtp.Send($message) 

La salida en la pantalla se ve así:

35 

FirstName LastName EMail        Count 
--------- -------- -----        ----- 
John  Doe  [email protected]      51 
Jane  Doe  [email protected]      20 

... pero el cuerpo del correo electrónico tiene el siguiente aspecto:

Here is a listing of open issues in IssueTrak, sorted by Next Action. 

Microsoft.PowerShell.Commands.Internal.Format.FormatStartData Microsoft.PowerShell.Commands.Internal.Format.GroupStartData 

Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData 

...y así. ¿Qué estoy haciendo mal?

Respuesta

10

Así es como yo lo haría:

# Create a DataTable 
$table = New-Object system.Data.DataTable "TestTable" 
$col1 = New-Object system.Data.DataColumn Name,([string]) 
$col2 = New-Object system.Data.DataColumn Dept,([string]) 
$table.columns.add($col1) 
$table.columns.add($col2) 

# Add content to the DataTable 
$row = $table.NewRow() 
$row.Name = "John" 
$row.Dept = "Physics" 
$table.Rows.Add($row) 
$row = $table.NewRow() 
$row.Name = "Susan" 
$row.Dept = "English" 
$table.Rows.Add($row) 

# Create an HTML version of the DataTable 
$html = "<table><tr><td>Name</td><td>Dept</td></tr>" 
foreach ($row in $table.Rows) 
{ 
    $html += "<tr><td>" + $row[0] + "</td><td>" + $row[1] + "</td></tr>" 
} 
$html += "</table>" 

# Send the email 
$smtpserver = "smtpserver.domain.com" 
$from = "[email protected]" 
$to = "[email protected]" 
$subject = "test" 
$body = "Hi there,<br />Here is a table:<br /><br />" + $html 
Send-MailMessage -smtpserver $smtpserver -from $from -to $to -subject $subject -body $body -bodyashtml 
+1

+1 por usar send-mailmessage con -bodyAsHTML –

+0

Lo intenté, pero recibo errores. Compartí el código completo, ¿quizás puedes ver lo que estoy haciendo mal? –

+0

OK, lo primero es deshacerse de: '$ DataSet.Tables | Format-Table -Auto' porque eso no hace nada. Necesita tomar '$ DataSet' y obtener una DataTable,' $ table = $ DataSet.Tables [0] '. Una vez que tenga DataTable, use mi ejemplo para crear manualmente la cadena $ html. –

2

Puede tratar (no probado):

$message.Body = $message.Body + ($DataSet.Tables | format-Table -auto | convertto-html) 
+0

que no parecía para ayudar, ahora todo lo que estoy recibiendo en el correo electrónico es una lista de los números GUID-como ... –

+0

esto funcionará, pero debe seleccionar las columnas específicas que desea en su tabla porque el objeto de tabla de datos incluye todo tipo de propiedades integradas, además de sus columnas personalizadas. es decir $ tabla | seleccione col1, col2, colN | convertto-html –

0

respuesta generalizada:

$body+=($variable|Select-Object property1,property2|ConvertTo-Html)

+0

Esto no proporciona una respuesta a la pregunta. Una vez que tenga suficiente [reputación] (https://stackoverflow.com/help/whats-reputation) podrá [comentar cualquier publicación] (https://stackoverflow.com/help/privileges/comment); en su lugar, [brinde respuestas que no requieran aclaración del autor de la pregunta] (https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can- i-do-instead). - [De la crítica] (/ review/low-quality-posts/16774381) – OmG

Cuestiones relacionadas