Powershell处理空值

时间:2014-10-14 10:20:16

标签: powershell

Hello我的脚本在以下行返回null值错误 “尺寸MB超过180天”= $ MbxSearch.ResultItemsSize.Value.ToMB() 因为某些用户的邮箱中没有符合以下搜索查询的邮件 AND收到:< $('01/03/2014 23:59:59')

如何处理数组/哈希表中的“您无法在空值表达式上调用方法”错误。

任何帮助都会受到极大的关注。

这是我的剧本

$Results = @()
$MailboxUser = Get-Content D:\Mike_X\Import\MbxUsers.txt
$MailboxUser | ForEach {
$Mailbox = Get-Mailbox $_
$MbxStatsArchive = Get-MailboxStatistics -Archive $_
$MbxStats = Get-MailboxStatistics $_
$MbxSearch = Search-Mailbox -DoNotIncludeArchive -SearchQuery "Received: >     $('01/01/1980 00:00:00') AND Received: < $('01/03/2014 23:59:59')" -EstimateResultOnly $_

    $Properties = @{
    "Live Mailbox Name" = $Mailbox.DisplayName
    "Archive Mailbox Name" = $MbxStatsArchive.DisplayName
    "Archive Quota GB" = $Mailbox.ArchiveQuota.Value.ToGB()
    "Archive Size MB" = $MbxStatsArchive.TotalItemSize.Value.ToMB()
    "Archive Database" = $MbxStatsArchive.Database
    "Live Mailbox Size MB" = $MbxStats.TotalItemSize.Value.ToMB()
    "Items over 180 days old" = $MbxSearch.ResultItemsCount
    "Size MB over 180 days old" = $MbxSearch.ResultItemsSize.Value.ToMB()           

}

$Results += New-Object PSObject -Property $Properties

}

$Results | Select-Object "Live Mailbox Name","Live Mailbox Size MB","Archive Mailbox  Name","Archive Quota GB","Archive Size MB",`
"Archive Database","Items over 180 days old","Size MB over 180 days old" | FL

1 个答案:

答案 0 :(得分:0)

在构造HashTable之前测试它并将值赋给临时变量:

$SizeMB = 0
if($MbxSearch.ResultItemsSize.Value -ne $null)
{
    $SizeMB = $MbxSearch.ResultItemsSize.Value.ToMB()
}
$Properties = @{
    "Live Mailbox Name" = $Mailbox.DisplayName
    "Archive Mailbox Name" = $MbxStatsArchive.DisplayName
    "Archive Quota GB" = $Mailbox.ArchiveQuota.Value.ToGB()
    "Archive Size MB" = $MbxStatsArchive.TotalItemSize.Value.ToMB()
    "Archive Database" = $MbxStatsArchive.Database
    "Live Mailbox Size MB" = $MbxStats.TotalItemSize.Value.ToMB()
    "Items over 180 days old" = $MbxSearch.ResultItemsCount
    "Size MB over 180 days old" = $SizeMB
}