如何将powershell项添加到数组?

时间:2014-06-05 18:03:45

标签: powershell exchange-server

我的目标是在export-csv命令中使用以下命令的输出。

代码:

$all 

Foreach($mbx In Get-Mailbox)
 {
    $tmp=   [PSCustomObject]@{Name= $mbx; Company=$(Get-User $_).Company; ActiveSyncEnabled=$(Get-CASMailbox $_).ActiveSyncEnabled} 
    $all = $all + $tmp
}

当我运行上面的代码时,我收到以下错误:

Bad argument to operator '+': Item has already been added. Key in dictionary: 'Name'  Key being added: 'Name'.
At line:4 char:18
+     $all = $all + <<<<  $tmp
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : BadOperatorArgument

问题

如何正确创建新的PowerShell对象,或将其添加到数组中,以便将输出发送到不同的命令行开关?

4 个答案:

答案 0 :(得分:1)

[PSObject]不是有效的类型加速器。

更正后的脚本:

 $all =
 Foreach($_ In Get-Mailbox | select -first 10)
  {
   New-Object PSObject -Property @{Name= $_.Name; Company=$(Get-User $_.DistinguishedName).Company; ActiveSyncEnabled=$(Get-CASMailbox $_.Name).ActiveSyncEnabled} 
 }

 $all | 
 select Name,Company,ActiveSyncEnabled |
 Export-Csv c:\somedir\mailboxinfo.csv -NoTypeInformation

答案 1 :(得分:1)

我建议用$ mailbox等替换你叫$ _的变量。

答案 2 :(得分:1)

以下命令将自定义项添加到数组

 $array = @()

Foreach($_ In Get-Mailbox -resultsize unlimited )
 {
    $object = New-Object -TypeName PSObject
    $object | Add-Member -Name 'Name' -MemberType Noteproperty -Value $_.Name
    $object | Add-Member -Name 'Company' -MemberType Noteproperty -Value (Get-User $_.DistinguishedName).Company
    $object | Add-Member -Name 'ActiveSyncEnabled' -MemberType Noteproperty -Value (Get-CASMailbox $_.Name).ActiveSyncEnabled
   $array += $object 
}


$array | Export-Csv c:\somedir\mailboxinfo.csv -NoTypeInformation

答案 3 :(得分:0)

我会将ForEach包装在子表达式中。

$(
Foreach($_ In Get-Mailbox | select -first 10)
 {
   [PSCustomObject]@{Name= $_.Name; Company=$(Get-User $_.DistinguishedName).Company; ActiveSyncEnabled=$(Get-CASMailbox $_.Name).ActiveSyncEnabled} 

}) | Export-Csv c:\somedir\mailboxinfo.csv -NoTypeInformation