如何使用powershell在邮件主题中添加日期

How to add a date in mail subject using powershell

我正在编写一个脚本,用于从 Microsoft 安全合规中心搜索过去 7 天的审核日志报告。该脚本将在每个星期日晚上 运行 向我的经理发送该周的报告。

在我的脚本中,我有一个非常基础的主题,但我正在考虑在主题中添加一个日期范围,这样它会更有帮助,但我不确定该怎么做,所以我会非常感谢如果我能得到帮助或建议。

我想在主题中添加一些内容,例如“2021 年 11 月 22 日至 2021 年 11 月 28 日的审计日志报告”


$logFile = "C:\AuditLogSearch\AuditLogSearchLog.txt"
$outputFile = "C:\AuditLogSearch\AuditLogRecords.csv"
[DateTime]$start = [DateTime]::UtcNow.AddDays(-7)
[DateTime]$end = [DateTime]::UtcNow
$record = "Discovery"
$resultSize = 5000
$intervalMinutes = 60


#####################
#  Send Automatic Email
#####################


$OL = New-Object -ComObject outlook.application
Start-Sleep 5
$mItem = $OL.CreateItem("olMailItem")

$mItem.To = "jj@gmail.com"
$mItem.Subject = "Weekly Audit Log Report"
$mItem.Attachments.Add("C:\AuditLogSearch\AuditLogSearchLog.txt")
$mItem.Body = "SENT FROM POWERSHELL"

$mItem.Send()

通过使用 .ToShortDateString() 你可以获得你想要的输出。

...
$mItem.Subject = "Weekly Audit Log Report $($start.ToShortDateString()) - $($end.ToShortDateString())"
...

您已经拥有必要的部分:

[DateTime]$start = [DateTime]::UtcNow.AddDays(-7)
[DateTime]$end = [DateTime]::UtcNow

只需将 $mItem.Subject = "Weekly Audit Log Report" 更改为:

$mItem.Subject = "Audit Log report from {0}-{1}" -f
$start.ToShortDateString(), $end.ToShortDateString()