scriptblock不返回任何值

时间:2018-08-14 07:00:30

标签: powershell

在下面的脚本$recexternal$recinternal中,总是返回,好像第二个块有问题。 但是,第一个成功执行并获得正确的$i$e输出。 我在做什么错了?

Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010

$e = 0;
$i = 0;
$recexternal = 0;
$recinternal = 0;
$array = @("JayanManniath.Nair@contoso.com")
foreach ($user in $array) {
    $sender = Get-TransportServer |
              Get-MessageTrackingLog -ResultSize Unlimited -Sender $user 
    $sender | %{
        if (($_.Source -eq "SMTP") -and ($_.EventId -eq "SEND")) {$e++}
        if (($_.Source -eq "STOREDRIVER") -and ($_.EventId -eq "DELIVER")) {$i++}
    }

    $recipient = Get-TransportServer |
                 Get-MessageTrackingLog -ResultSize Unlimited -Recipients $user
    $reipient | %{
        if (($_.Source -eq "SMTP") -and ($_.EventId -eq "RECEIVE")) {$recexternal++}
        if (($_.Source -eq "STOREDRIVER") -and ($_.EventId -eq "DELIVER" )) {$recinternal++}
    }
}

Write-Host "$user has sent $i emails internally"
Write-Host "$user has sent $e emails externally"
Write-Host "$user has received $recexternal emails from outside organization"
Write-Host "$user has received $recinternal emails from inside the organization"

1 个答案:

答案 0 :(得分:0)

除了明显的拼写错误之外,您的代码还错误地放置了输出,
如果$user中有多个$array,则写入主机命令
应该放在ForEach内。

使用Where-Object().count代替
ForEach-Object%)和IF可能更有效。

Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010

$array = @("JayanManniath.Nair@contoso.com")
ForEach ($user in $array) {
    $sender = Get-TransportServer |
              Get-MessageTrackingLog -ResultSize Unlimited -Sender $user 

    $e = ($sender | Where-Object {($_.Source  -eq "SMTP") -and 
                                  ($_.EventId -eq "SEND")} ).Count
    $i = ($sender | Where-Object {($_.Source  -eq "STOREDRIVER") -and 
                                  ($_.EventId -eq "DELIVER")} ).Count

    $recipient = Get-TransportServer |
                 Get-MessageTrackingLog -ResultSize Unlimited -Recipients $user

    $recexternal = ($recipient | Where-Object {($_.Source  -eq "SMTP") -and 
                                               ($_.EventId -eq "RECEIVE")} ).Count
    $recinternal = ($recipient | Where-Object {($_.Source  -eq "STOREDRIVER") -and 
                                               ($_.EventId -eq "DELIVER")} ).Count

    Write-Host "$user has sent $i emails internally"
    Write-Host "$user has sent $e emails externally"
    Write-Host "$user has received $recexternal emails from outside organization"
    Write-Host "$user has received $recinternal emails from inside the organization"
}