Exchange foreach from csv


I am stuck and it really annoys me :slight_smile:

I want to create an txt file based on customattribute1. Thinking of using import-csv command to maintain customer naming. The logic around foreach is all wrong. Having some trouble to wrap my head around the foreach looping.

Can someone help ?

What i got is :

import-csv -path "c:\storage\customer.csv | Get-mailbox -resultsize unlimited | foreach ($customer in $customers) | where {$.customattribute1 -eq $customer} | Get-Mailboxstatistics | select displayname,TotalItemSize,ItemCount,@{expression={$.totalitemsize.value.ToMB()};label=“Size(MB)”} | sort-object TotalItemSize | out-file c:\report$customer.txt

There are two Foreach loops in PowerShell:

foreach ($i in $collection) { # do stuff with $i }

$collection | Foreach-Object { # do stuff with $_ }

You kind of have a mash of both, and I’m not quire sure what you’re trying to achieve. I assume $customers is a collection you’ve declared elsewhere and you want to filter mailboxes to those included in it? If so, you don’t even need a foreach as the pipeline is handling it for you:

import-csv -path "c:\storage\customer.csv | 
Get-mailbox -resultsize unlimited | 
where {$customers -contains $_.customattribute1} | 
Get-Mailboxstatistics | 
select displayname,TotalItemSize,ItemCount,@{expression={$_.totalitemsize.value.ToMB()};label="Size(MB)"} | 
sort-object TotalItemSize | 
out-file c:\report\$customer.txt

To use a foreach loop in this script you would replace your Where statement with

foreach-object { if ($customers -contains $.customattribute1) { $ } } |

This is saying to loop through each item, and if it’s contained in $customers then send it on through the pipeline.

To be honest I’ve not had any opportunity to work with PowerShell and Exchange so I can’t say much on piping a CSV to Get-Mailbox, I can only assume it works.