Powershell ForEach导出问题



首先,我要感谢您分享的所有知识。第二,如果这是以前发布的,我想提前道歉。

我对使用ForEach语句的PowerShell世界有点陌生。下面是我的查询,我只是试图将两个命令的结果合并到一个csv文件中。当我在一个电子邮件地址上这样做时,它工作得很好,但我得到了"System.Object[]">当尝试导出5个结果时-下面是结果的图像。

$OutputLarge1 = @()
$MailboxesLarge1  = Get-EXOmailbox -ResultSize 5 | Select 
DisplayName,Alias,UserPrincipalName,PrimarySmtpAddress 
$StatisticsLarge1 = Get-EXOMailbox -ResultSize 5 | Get-EXOmailboxstatistics  | Select 
Displayname,DeletedItemCount,ItemCount
Foreach ($i in $MailboxesLarge1) {
$OutputLarge1 += [PSCustomObject] @{
DisplayName          = $MailboxesLarge1.DisplayName
Alias                = $MailboxesLarge1.Alias
PrincipalName        = $MailboxesLarge1.UserPrincipalName
PrimarySmtpAddress   = $MailboxesLarge1.PrimarySmtpAddress
DeletedItemCount     = $StatisticsLarge1.DeletedItemCount
ItemCount            = $StatisticsLarge1.ItemCount
}
}
$OutputLarge1 | Export-Csv C:ForEachTestLarge.csv -NoTypeInformation

CSV导出的图像

如能为我指明正确的方向,我们将不胜感激。

谢谢

这是因为迭代没有按预期工作。有两个问题。让我们仔细看看代码中添加的注释:

# Iterate all members of $MailboxesLarge1 collection
# On each iteration, $i will contain an object
Foreach ($i in $MailboxesLarge1) {
# Add new element to $OutputLarge1
$OutputLarge1 += [PSCustomObject] @{
# DisplayName property will get a value of the whole collection
# instead of iterated item $i
DisplayName          = $MailboxesLarge1.DisplayName
Alias                = $MailboxesLarge1.Alias
PrincipalName        = $MailboxesLarge1.UserPrincipalName
PrimarySmtpAddress   = $MailboxesLarge1.PrimarySmtpAddress
DeletedItemCount     = $StatisticsLarge1.DeletedItemCount
ItemCount            = $StatisticsLarge1.ItemCount
}
}

第一期。

因此,对于每一个项目$i,您都会意外地将整个集合的项目分配给输出对象。

修复很容易,请参考循环中的迭代器对象。

第二个问题是,统计数据在另一个a集合中,而这些数据被访问时也出现了同样的错误。但还有更多:结果集之间没有联系。我手头没有Exchange,但我确信不能保证结果集是有序的。要保持结果集不变,请将邮箱保存在一个变量中并传递。像这样,

$boxes = Get-EXOmailbox -ResultSize 5 
$MailboxesLarge1  = $boxes|Select DisplayName,Alias,UserPrincipalName,PrimarySmtpAddress 
$StatisticsLarge1 = $boxes|Get-EXOmailboxstatistics |Select  Displayname,DeletedItemCount,ItemCount

最新更新