Powershell: how to format Get-Childitem for email?

Question:

Simply put, I’m trying to send an email from a Powershell script which lists the contents of a directory.

In order to do this, I’m storing text in a variable, then inserting this variable into Send-MailMessage.

My problem is this. When I pipe the object to Out-String as follows, it doesn’t insert newlines:

Obviously, when Get-Childitem is entered at the prompt, the output is nicely formatted with newlines, however when stored to a variable then emailed (in an HTML email), there are no newlines, which results in an unreadable, long string of filenames.

How do I do this?

Answer:

You can use the ConvertTo-Html cmdlet to do this:

It will create a nice table for you that can be sent in an HTML email. The -fragment part removes the head and body etc. and gives only the table.

Source:

Powershell: how to format Get-Childitem for email? by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply