我正在编写一个PowerShell脚本,可以在几天的列表中查询我们的Exchange服务器上每日的 SENT 电子邮件数量。
我想在excel文件中输出结果,以便我可以进行更多分析(数据透视表等)。
我遇到的问题是我几天都很难编码,但希望这可以灵活运行几个月。
$StartTime = (Get-Date -Hour 00 -Minute 00 -Second 00).AddDays(-7),
$EndTime = (Get-Date -Hour 23 -Minute 59 -Second 59).AddDays(-1),
ForEach ($Email in $FilterArr) {
$MTL = Get-MessageTrackingLog -Start $StartTime -End $EndTime -EventId SEND -ResultSize Unlimited -Sender $Email.Email
[Int]$Day0Mail = ($MTL | Where-Object {($_.Timestamp -gt $ArrayStartDates[0]) -And ($_.Timestamp -lt (Get-Date $ArrayStartDates[0] -Hour 23 -Minute 59 -Second 59))}).Count
[Int]$Day1Mail = ($MTL | Where-Object {($_.Timestamp -gt $ArrayStartDates[1]) -And ($_.Timestamp -lt (Get-Date $ArrayStartDates[1] -Hour 23 -Minute 59 -Second 59))}).Count
...
$MailObj = New-Object -TypeName psobject -Property ([Ordered]@{
Name = $Email.Name
Email = $Email.Email
[String]$ArrayStartDates[0].ToShortDateString() = $Day0Mail
[String]$ArrayStartDates[1].ToShortDateString() = $Day1Mail
....
$ReportArr += $MailObj
}
$ReportArr | Export-Csv -NoTypeInformation -Path $ReportPath -Force
答案 0 :(得分:0)
你有几个选择。您可以在这些区域周围添加Param()
块:
Param(
$StartTime = (Get-Date -Hour 00 -Minute 00 -Second 00).AddDays(-7),
$EndTime = (Get-Date -Hour 23 -Minute 59 -Second 59).AddDays(-1)
)
哪个会保留默认设置,但如果你想覆盖它们,你可以像这样运行你的脚本:
.\YourScript.ps1 -StartTime 01/02/2017 -EndTime (get-date)
或者,如果您只是希望灵活处理之前收集数据的天数,请在现有代码上方添加一个像这样的Param块:
Param($Days = 7)
然后按如下方式更改此行:
$StartTime = (Get-Date -Hour 00 -Minute 00 -Second 00).AddDays(-$Days)
再次,像这样运行脚本:
.\YourScript.ps1 -Days 180
或者,如果您不想使用参数执行此操作,则可以使用$Days
解决方案,但使用Read-Host
代替:
$Days = Read-Host "How many days history do you want?"
$StartTime = (Get-Date -Hour 00 -Minute 00 -Second 00).AddDays(-$Days)
根据评论,要处理代码的其他重复部分,请确保您拥有$Days
参数,然后可以添加内部ForEach
循环:
$MailObj = New-Object -TypeName psobject -Property ([Ordered]@{
Name = $Email.Name
Email = $Email.Email
})
0..$Days | ForEach-Object {
$DayMail = 0
$Day = $_
[int]$DayMail = ($MTL | Where-Object {($_.Timestamp -gt $ArrayStartDates[$Day]) -And ($_.Timestamp -lt (Get-Date $ArrayStartDates[$Day] -Hour 23 -Minute 59 -Second 59))}).Count
$MailObj | Add-Member -MemberType NoteProperty -Name ($ArrayStartDates[$Day].ToShortDateString()) -Value $DayMail
}