Powershell:如何格式化 Get-Childitem 的电子邮件?

发布于 2024-12-27 19:50:15 字数 460 浏览 0 评论 0原文

简而言之,我正在尝试从列出目录内容的 Powershell 脚本发送一封电子邮件。

为了做到这一点,我将文本存储在一个变量中,然后将该变量插入到 Send-MailMessage 中。

我的问题是这样的。当我按如下方式将对象通过管道传输到 Out-String 时,它不会插入换行符:

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

显然,当在提示符下输入 Get-Childitem 时,输出的格式很好带有换行符,但是当存储到变量然后通过电子邮件发送(在 HTML 电子邮件中)时,没有换行符,这会导致无法读取的长文件名字符串。

我该怎么做?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

谁对谁错谁最难过 2025-01-03 19:50:15

您可以使用 ConvertTo-Html cmdlet 来执行此操作:

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

它将为您创建一个可以在 HTML 电子邮件中发送的漂亮表格。 -fragment 部分删除了头部和身体等,只给出了表格。

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.

莳間冲淡了誓言ζ 2025-01-03 19:50:15

使用 ConvertTo-Html cmdlet 怎么样?填写您的环境信息。

$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

编辑 - 这可行,但电子邮件看起来很糟糕。如果您希望它看起来与在 PowerShell 窗口中执行 dir 时完全相同,请使用以下命令:

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

How about using the 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:

[string] $html = dir $path | Select Mode, LastWriteTime, Length, Name | ConvertTo-Html 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文