In this small post I’ll quickly show you how to take almost any output from PowerShell and turn it into a presentable report and send it as an email.
The below code takes advantage of PSCustomObjects and the ability to store them inside of arrays, thus removing the issue of having multiple keys with the same name in a hash table/PSCustomObject.
$Items = Get-ChildItem C:\temp\ExampleFiles\* $Table = @() foreach ($Item in $Items) { $Output = [PSCustomObject]@{ Mode = $Item.Mode LastWriteTime = $Item.LastWriteTime Length = $Item.Length Name = $Item.Name } $Table += $Output } $TableOutput = $Table.GetEnumerator() | Select-Object * | ConvertTo-Html -Fragment -As Table $Body = @" <head> <style type='text/css'> table { border-collapse: collapse; } th { text-align: center; padding: 0.5em; background-color: teal; color:white } tr,td { text-align: center; border-bottom: .15em solid #ddd; padding-left: 3em; padding-right: 3em; } </style> </head> <body> $TableOutput </body> "@ $EmailSplat = @{ To = 'email@yourdomain.org' From = 'email@yourdomain.org' Subject = 'Example' Body = $Body BodyAsHTML = $true UseSSL = $true SMTPServer = 'YourSMTPServer' } Send-MailMessage @EmailSplat
Keep in mind that this is simply an example, you can transform, manipulate, and modify the data however you wish before you add it to the PSCustomObject.
Output in PowerShell Report in Email