[英]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. 简而言之,我正在尝试从Powershell脚本发送一封电子邮件,其中列出了目录的内容。
In order to do this, I'm storing text in a variable, then inserting this variable into Send-MailMessage
. 为此,我将文本存储在变量中,然后将此变量插入
Send-MailMessage
。
My problem is this. 我的问题是这个。 When I pipe the object to
Out-String
as follows, it doesn't insert newlines: 当我按如下方式将对象传递给
Out-String
,它不会插入换行符:
$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. 显然,当在提示符下输入
Get-Childitem
时,输出很好地用换行符格式化,但是当存储到变量然后通过电子邮件发送(在HTML电子邮件中)时,没有新行,这会导致一个不可读的长文件名字符串。
How do I do this? 我该怎么做呢?
You can use the ConvertTo-Html
cmdlet to do this: 您可以使用
ConvertTo-Html
cmdlet执行此操作:
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. 它将为您创建一个可以在HTML电子邮件中发送的好桌子。 The
-fragment
part removes the head and body etc. and gives only the table. -fragment
部分删除头部和身体等,只给出表格。
How about using the ConvertTo-Html
cmdlet? 如何使用
ConvertTo-Html
cmdlet? Fill in your environment info. 填写您的环境信息。
$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 - This works, but the email looks like crap. 编辑 - 这是有效的,但电子邮件看起来像垃圾。 If you want it to look exactly like it does when you do a
dir
in the PowerShell window use this: 如果您希望它看起来与在PowerShell窗口中执行
dir
时的效果完全相同,请使用以下命令:
[string] $html = dir $path | Select Mode, LastWriteTime, Length, Name | ConvertTo-Html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.