Powershell: how to format Get-Childitem for email?

Simply put, I'm trying to send an email with a Powershell script that lists the contents of a directory.

To do this, I save the text in a variable, and then paste this variable into Send-MailMessage .

My problem is this. When I wrap an object on an Out-String as follows, it does not insert new lines:

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

Obviously, when Get-Childitem is entered at Get-Childitem , the output is well formatted using newlines, however when saved in a variable then sent via email (in HTML email), there are no newlines, which results in an unreadable length of the name string files.

How to do it?

+4
source share
2 answers

The ConvertTo-Html cmdlet can be used to do this:

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

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

+6
source

What about using the ConvertTo-Html cmdlet? Enter information about your environment.

 $path = "C:\" [string] $html = dir $path | ConvertTo-Html $smptServer = '' $to = '' $from = '' $subject = 'Test' Send-MailMessage -To $to -From $from -Body $html -BodyAsHtml -SmtpServer $smptServer -Subject $subject 

EDIT - It works, but the letter looks like shit. If you want it to look exactly as if you were doing a dir in a PowerShell window, use this:

 [string] $html = dir $path | Select Mode, LastWriteTime, Length, Name | ConvertTo-Html 
+2
source

Source: https://habr.com/ru/post/1391686/


All Articles