1

I'm writing a powershell script that queries our Exchange server for the daily number of SENT emails over a list of several days.

I would like to output the results in an excel file so I can do so more analysis (pivot tables etc).

The issue I have is I'm hard coding several days but want this to be flexible to run it over several months.

$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
4

1 回答 1

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
}
于 2017-05-09T11:09:54.153 回答