Once in a while I need to do some Windows management. This time I needed to extract a list of all mail addresses in specific active directory containers. Both the "Primary address" and "Alternate addresses" will be fetched and placed in C:\.txt: $countrylist = "DK","NO","SE" $oulist = "user","ExchangeAccounts" Write-Output "------------------------" Write-Output "Fetching mail addresses." Write-Output "------------------------" foreach ($country in $countrylist) { Write-Output "Clearing file C:\$country.txt" If (Test-Path C:\$country.txt){ Clear-Content C:\$country.txt } foreach ($ou in $oulist) { Write-Output "Getting data for $ou in $country and appending it to C:\$country.txt" $mailaddr = Get-Mailbox -OrganizationalUnit "ou=$ou,ou=$country,dc=AD,dc=EXAMPLE,dc=COM" -ResultSize Unlimited |Select-Object PrimarySmtpAddress, @{Name="EmailAddresses";Expression={$_.EmailAddresses |Where-Object {$_.PrefixString -ceq "smtp"}}} $mailaddr | ForEach-Object {$_.PrimarySmtpAddress} | Add-Content C:\$country.txt $mailaddr | ForEach-Object {$_.EmailAddresses -replace("smtp:", "")} | Add-Content C:\$country.txt } }