问题描述
我是 Powershell 的新手,所以请耐心等待。
我正在尝试编写一个 powershell 脚本,该脚本将扫描 Exchange 2010 中的多个邮箱并将收到的最后日期写入现有的 CSV 文件。 由于服务器运行的是 Exchange 2010,它具有 PowerShell v2,因此我无法使用 PS v3 中可用的 -Append 参数,因此我尝试使用 out-file 和 Add-Content,但两者都失败并出现下面列出的错误脚本的第二次运行。 我假设我在导入或写入现有 CSV 文件时做错了什么,但我无法弄清楚究竟是什么。
# Path to the CSV file. This needs to be in place before the scrpt runs
$results = Import-CSV -Path 'C:\temp\numberofmails.csv' -Header "MailBox","TotalItems","LastReceived",# go through the mabList array and get the identity,number of items and last received date and time
Foreach($i in $mbxList){
$data = Get-MailBoxFolderStatistics -Identity $i -IncludeOldestAndNewestItems | Where {$_.Name -match "InBox"} |select identity,ItemsInFolder,NewestItemReceivedDate
$mbID=$data.identity
$numItems=$data.ItemsInFolder
$lastReceived=$data.NewestItemReceivedDate
#Append data to the CSV file using PS v2 so cannot use append as can be done in v3
$exp = $results
$exp.MailBox = $mbID
$exp.TotalItems = $numItems
$exp.LastReceived = $LastReceived
#$exp | ConvertTo-CSV -NoTypeinformation | Select-Object -Skip 1| Out-File -Append 'C:\temp\numberofmails.csv'
$exp | ConvertTo-CSV -NoTypeinformation | Select-Object -Skip 1| Add-Content 'C:\temp\numberofmails.csv' -Encoding UTF8
}
第二次运行脚本时收到错误。
Property 'MailBox' cannot be found on this object; make sure it exists and is settable.
At C:\Temp\ReceivedItemsv2.ps1:29 char:6
+ $exp. <<<< MailBox = $mbID
+ CategoryInfo : InvalidOperation: (:) [],RuntimeException
+ FullyQualifiedErrorId : PropertyAssignmentException
Property 'TotalItems' cannot be found on this object; make sure it exists and is settable.
At C:\Temp\ReceivedItemsv2.ps1:30 char:6
+ $exp. <<<< TotalItems = $numItems
+ CategoryInfo : InvalidOperation: (:) [],RuntimeException
+ FullyQualifiedErrorId : PropertyAssignmentException
Property 'LastReceived' cannot be found on this object; make sure it exists and is settable.
At C:\Temp\ReceivedItemsv2.ps1:31 char:6
+ $exp. <<<< LastReceived = $LastReceived
+ CategoryInfo : InvalidOperation: (:) [],RuntimeException
+ FullyQualifiedErrorId : PropertyAssignmentException
解决方法
$results
是具有 Mailbox
、TotalItems
和 LastReceived
属性的对象集合。您可以选择向该集合添加新对象,也可以过滤其中一个对象并更改其属性值。您似乎想创建一个新对象,将其转换为 CSV,然后将其附加到文本文件中。
# Run this code inside of the foreach loop
# Create new object with desired properties
$exp = "" | Select-Object Mailbox,TotalItems,LastReceived
# Set property values
$exp.Mailbox = $mbID
$exp.TotalItems = $numItems
$exp.LastReceived = $LastReceived
# Append object to CSV file
$exp | ConvertTo-CSV -NoTypeInformation |
Select-Object -Skip 1 |
Add-Content 'C:\temp\numberofmails.csv' -Encoding UTF8