Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell: how to format Get-Childitem for email?

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:

$mailbody += "<p>" + (get-childitem $path | select-object Name | Out-String -width 40) + "</P>"

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?

like image 277
hazymat Avatar asked Jan 18 '23 18:01

hazymat


1 Answers

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

get-childitem $path | select-object Name | ConvertTo-Html -fragment

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.

like image 175
manojlds Avatar answered Jan 28 '23 01:01

manojlds