【问题标题】:Powershell ForEach Export IssuesPowershell ForEach 导出问题
【发布时间】:2022-01-24 05:41:30
【问题描述】:

第一,我要感谢您分享的所有知识。 第二,如果之前已经发布过,我想提前道歉。

我对使用 ForEach 语句的 PowerShell 世界有点陌生。下面是我的查询,我只是想将 2 个命令的结果合并到 1 个 csv 文件中。当我在单个电子邮件地址上执行此操作时效果很好,但在尝试导出 5 个结果时我得到 "System.Object[]" - 下面是结果图像。

$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

Image of CSV Export

任何提示我正确方向的提示将不胜感激。

谢谢

【问题讨论】:

    标签: powershell foreach


    【解决方案1】:

    发生这种情况是因为迭代未按预期工作。有两个问题。让我们仔细看看代码中添加的 cmets:

    # 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,您不小心将整个集合的项目价值分配给了输出对象。

    修复很简单,参考循环内的迭代器对象。

    第二个问题是统计数据在另一个集合中,并且正在以同样的错误访问这些数据。但还有更多:结果集之间没有联系。我手头没有 Exchange,但我很确定不能保证结果集是有序的。要保持结果集相同,请将邮箱保存在一个变量中并传递它。像这样,

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-22
      • 2017-07-03
      • 1970-01-01
      • 1970-01-01
      • 2021-05-25
      • 2022-01-12
      • 2022-10-17
      • 1970-01-01
      相关资源
      最近更新 更多