List all mailboxes that forward to a specific user - powershell

I have this script that lists all mailboxes that are forwarding email, however, I am curious if there would be a way to make it return all mailboxes that forward to a specific user. Basically I'm trying to find out every mailbox that forwards mail to "johndoe". Any help would be greatly appreciated! This is for exchange 2007 btw...
Here's the script so far:
$fwds = get-mailbox | Where-Object { $_.ForwardingAddress -ne $null }
| select Name, ForwardingAddress
foreach ($fwd in $fwds) {$fwd | add-member -membertype noteproperty
-name “ContactAddress” -value (get-contact $fwd.ForwardingAddress).WindowsEmailAddress}
$fwds

Exchange uses CanonicalName for the forwarding address, so you'll need to look that up from the user name. Since it could be a Mailbox, DL, or Contact, the easiest way I know of is to use Get-Recipient, and grab the Identity property.
$RecipientCN = (get-recipient johndoe).Identity
get-mailbox | Where-Object { $_.ForwardingAddress -eq $RecipientCN }

#mjolinor's version works, but is rather slow, since it loads all the mailboxes. On my system it took about 30 seconds to go through ~300 mailboxes.
This can be speed up by adding a filter to the Get-Mailbox command to only return ones that are actually being forwarded, like so:
$RecipientCN = (get-recipient johndoe).Identity
Get-Mailbox -ResultSize Unlimited -Filter {ForwardingAddress -ne $null} | Where-Object {$_.ForwardingAddress -eq $RecipientCN}
But wait, we can get even faster! Why not search for the correct user right in the filter? Probably because it's hard to get the syntax right, because using variables in -Filter gets confusing.
The trick is to use double quotes around the entire filter expression, and single quotes around the variable:
$RecipientCN = (get-recipient johndoe).Identity
Get-Mailbox -ResultSize Unlimited -Filter "ForwardingAddress -eq '$RecipientCN'"
This version returns the same results in 0.6s - about 50 times faster.

Related

Using filter to find email addresses matching a domain

I'm trying to find email addresses in O365 Exchange that matches a particular domain using PowerShell.
If I use:
Get-Recipient -ResultSize unlimited -filter '(PrimarySMTPAddress -like "*smith*")' | fl primarysmtpaddress
I get all the addresses that have the string
If I use:
Get-Recipient -ResultSize unlimited -filter '(PrimarySMTPAddress -like "*#domain*")' | fl primarysmtpaddress
I get no results.
It looks like nothing is matched after the #.
I want to use -filter rather than a where statement because it is so much faster.
I was able to reproduce your issue. It seems to be related to the the specific attribute you filtered on, "PrimarySMTPAddress".
I was able to get the filter statement to return results by changing it to leverage "EmailAddresses", another attribute the email address is stored in:
Get-Recipient -ResultSize unlimited -filter '(EmailAddresses -like "*#domain*")' | fl primarysmtpaddress
Something else I saw of note: the "filterable properties" documentation mentions avoiding using "PrimarySMTPAddress" for another reason that I didn't know of:
Don't use the PrimarySmtpAddress property; use the EmailAddresses property instead. Any filter that uses the PrimarySmtpAddress property will also search values in the EmailAddresses property. For example, if a mailbox has the primary email address dario#contoso.com, and the additional proxy addresses dario2#contoso.com and dario3#contoso.com, all of the following filters will return that mailbox in the result: "PrimarySmtpAddress -eq 'dario#contoso.com'", "PrimarySmtpAddress -eq 'dario2#contoso.com'", or "PrimarySmtpAddress -eq 'dario3#contoso.com'".
Source
https://learn.microsoft.com/en-us/powershell/exchange/filter-properties?view=exchange-ps

PowerShell Office 365 Script to get user and mailbox information together

I am brand new to PowerShell (started this morning). I have successfully connected to my Office 365 and have been able to get lists of users from Office 365 and mailbox fields from the Exchange portion. What I can't figure out is how to combine them.
What I am looking for is the ability to export certain fields from the mailbox object but only for those mailboxes that belong to a non-blocked, licensed Office 365 users. We have a lot of users whose mailboxes have not been removed but they may no longer be licensed or they may be blocked.
Here are the two exports I have running now. They are complete exports. I tried to filter to the Office 265 users by isLicensed but I never got any results so I just downloaded everything and post processed them with Excel. But I need to run this on a regular basis...
Here's the code:
Get-Mailbox -ResultSize Unlimited | Select-Object DisplayName,Name,PrimarySMTPAddress,CustomAttribute2 | Export-CSV C:\temp\o365\mailboxes.csv
Get-MsolUser -all | Select-Object SignInName, DisplayName, Office, Department, Title, IsLicensed | export-csv c:\temp\o365\Users.csv
Any assistance would be appreciated.
Okay, so as I understand what you're trying to do... You want to get a list of all O365 users for whom the IsLicensed property is $true and the BlockCredential property is $false. Of those users, you then want to pull some data from their mailbox objects; DisplayName, Name, PrimarySMTPAddress, and CustomAttribute2.
There are a couple of ways that we can do this. The first is easier to throw together in the shell but takes longer to actually run. The second requires some set up but completes quickly.
First method
Since we know what our criteria is for what we want from Get-MsolUser, we'll use the pipeline to pull out what we want and toss it straight into Get-Mailbox.
Get-MsolUser -All | Where-Object {$_.IsLicensed -eq $true -and $_.BlockCredential -eq $false} |
Select-Object UserPrincipalName |
ForEach-Object {Get-Mailbox -Identity $_.UserPrincipalName | Select-Object DisplayName,Name,PrimarySMTPAddress,CustomAttribute2}
O365 PowerShell doesn't like giving us ways to filter our initial query, so we handle that in the second step, here...
Where-Object {$_.IsLicensed -eq $true -and $_.BlockCredential -eq $false}
This means, for each item passed in from Get-MsolUser -All, we only want those which have the properties Islicensed set to $true and BlockCredential set to $false.
Now, we only care about the results of Get-MsolUser in so far as determining what mailboxes to look up, so we'll grab a single property from each of the objects matching our prior filter.
Select-Object UserPrincipalName
If you only run everything up to this point, you'd get a list of UPNs in your shell for all of the accounts that we're now going to pipe into Get-Mailbox.
Moving on to our loop in this... If you haven't learned ForEach-Object yet, it's used to run a scriptblock (everything between the {}) against each item in the pipeline, one at a time.
Get-Mailbox -Identity $_.UserPrincipalName
Welcome to the pipeline operator ($_). Our previous Select-Object is feeding a collection of objects through the pipeline and this placeholder variable will hold each one as we work on them. Since these objects all have a UserPrincipalName property, we reference that for the value to pass to the Identity parameter of Get-Mailbox.
Sidebar
Here's a simple example of how this works..
PS> 1,2,3 | ForEach-Object {Write-Host $_}
1
2
3
Each item is passed along the pipeline, where we write them out one at a time. This is very similar to your standard foreach loop. You can learn more about their differences in this Scripting Guy post.
Moving on...
Select-Object DisplayName,Name,PrimarySMTPAddress,CustomAttribute2
We wrap it up with one last Select-Object for the information that you want. You can then look at the results in the shell or pipe into Export-Csv for working with in Excel.
Now... Since the pipeline works sequentially, there's some overhead to it. We're running a command, collecting the results, and then passing those results into the next command one at a time. When we get to our Get-Mailbox, we're actually running Get-Mailbox once for every UPN that we've collected. This takes about 2.5 minutes in my organization and we have less than 500 mailboxes. If you're working with larger numbers, the time to run this can grow very quickly.
Second method
Since a large amount of the processing overhead in the first method is with using the pipeline, we can eliminate most of it by handling our data collection as early and thoroughly as possible.
$Users = Get-MsolUser -All | Where-Object {$_.IsLicensed -eq $true -and $_.BlockCredential -eq $false} | Select-Object -ExpandProperty UserPrincipalName
$Mailboxes = Get-Mailbox | Select-Object UserPrincipalName,DisplayName,Name,PrimarySMTPAddress,CustomAttribute2
$Results = foreach ($User in $Users) {
$Mailboxes | Where-Object UserPrincipalName -eq $User
}
$Results | Export-Csv myFile.csv
The first 2 lines are pretty self-explanatory. We get all the user account info that we care about (just the UPNs) and then we grab all the mailbox properties that we care about.
foreach ($User in $Users)
Each entry in $Users will be stored in $User, where we'll then use it in the scriptblock that follows (in the {}).
$Mailboxes | Where-Object UserPrincipalName -eq $User
Each item in $Mailboxes is piped into Where-Object where we then check if the UserPrincipalName property is equal to the current value of $User. All of the matches are then stored in $Results, which can again be piped to Export-Csv for work in Excel.
While this method is harder to write out in the shell, and requires a little extra initial set up, it runs significantly faster; 22 seconds for my org, versus 2.5 minutes with the first method.
I should also point out that the use of UserPrincipalName with the mailbox dataset is simply to help ensure a solid match between those and the account dataset. If you don't want it in your final results, you can always pipe $Results into another Select-Object and specify only the properties that you care about.
Hope this helps!

Using Powershell to get Office 365 SMTP: email addresses

Found the exact script I need:
https://unlockpowershell.wordpress.com/2010/01/27/powershell-get-mailbox-display-smtp-addresses/
Get-Mailbox -ResultSize Unlimited |Select-Object DisplayName,ServerName,PrimarySmtpAddress, #{Name=“EmailAddresses”;Expression={$_.EmailAddresses |Where-Object {$_.PrefixString -ceq “smtp”} | ForEach-Object {$_.SmtpAddress}}}
When I run this using Powershell5 against Office 365, "Email Addresses" is returned blank.
Any ideas?
This may have worked on Exchange 2007/2010, where the blog post says it was tested, but O365 mailboxes are a little different.
The EmailAddresses property of a mailbox object in O365 is an array list containing strings and they have no PrefixString property here. The issue is at this point
Where-Object {$_.PrefixString -ceq “smtp”}
Since PrefixString doesn't exist, you get blank results.
Instead, since the EmailAddresses array is just a bunch of strings, you can filter on those directly.
Get-Mailbox -ResultSize Unlimited | Select-Object DisplayName,ServerName,PrimarySmtpAddress, #{Name=“EmailAddresses”;Expression={$_.EmailAddresses | Where-Object {$_ -clike “smtp*”}}}

Getting Calculated Expression to Display Properly in Powershell Exchange Command

So I have a command to look at all the mailboxes in my environment and return the oldest item in any folder that is not the "Contacts" folder of that particular mailbox. The whole thing seems to work except for the calculated expression that I threw in at the end of the command:
#{Name="Address";Expression={Get-Mailbox | ForEach-Object {$_.PrimarySmtpAddress}
The problem is this seems to return every Smtp Address for each line/object instead of one Smtp Address per line/object.
Here's the entire command:
Get-Mailbox | ForEach-Object {Get-MailboxFolderStatistics -IncludeOldestandNewestItems -Identity $_.Alias | Where-Object {($_.OldestItemReceivedDate -ne $null) -and ($_.FolderPath -ne "/Contacts")} | Sort OldestItemReceivedDate | Select First 1 OldestItemReceivedDate, Identity, #{Name="Address";Expression={Get-Mailbox | ForEach-Object {$_.PrimarySmptAddress}}}}
Ideally this would return the date of the oldest item, the folder where it was found, and the primary SMTP Address but it doesn't seem to be pulling only the corresponding SMTP Address. It looks like it's pulling every Primary SMTP Address every iteration. I'm sure it's something with my command but I can't figure out where. Any help would be much appreciated.
The calculated expression has access to the current pipeline object. However you are not using that when creating your expression. You are just calling every mailbox for each user as you have seen. Use the current pipeline object with $_. Get-Mailbox is smart enough to match needed values by property name.
#{Name="Address";Expression={Get-Mailbox $_ | ForEach-Object {$_.PrimarySmtpAddress}}}}
However you might be able to go about this is a different way. You already called all mailboxes at the start of your pipeline. No sense calling it a second time again.
Get-Mailbox | Select-Object Identity, #{Name="Address";Expression={$_.PrimarySmtpAddress}}, #{Name="OldestItemReceivedDate";Expression={
Get-MailboxFolderStatistics -IncludeOldestandNewestItems -Identity $_.Alias | Where-Object {
($_.OldestItemReceivedDate -ne $null) -and ($_.FolderPath -ne "/Contacts")} |
Sort-Object OldestItemReceivedDate |
Select-Object -ExpandProperty OldestItemReceivedDate -Last 1
}}
Now we have 2 calculated properties and we only need to call Get-Mailbox once for each user. You have some spelling mistakes and logic errors that I tried to fix. You will know if it does what you want.

Get SMTP address from a list of Names (Exchange 2013 powershell)

I'm trying to get SMTP address's for users who have OWAEnabled. I have what I think are two pieces that do what I want, but I can't figure out how to put them together. Ultimately it will output the SMTP address's to a CSV.
Get-CASMailbox -Filter{OWAEnabled -eq $true} | Select-Object Name
This gets me a list of user "Names" who have OWA enabled.
Get-Mailbox -ResultSize Unlimited | Select-Object PrimarySmtpAddress
This gets me Primary SMTP Address's
How do I put the two together? Sorry, i'm relatively new to PS.
Thanks for any help! :)
PrimarySMTPAddress is already a property of a CASMailbox object, so you just need to select it:
Get-CASMailbox -Filter{OWAEnabled -eq $true} | Select-Object Name,PrimarySMTPAddress
Most objects will have properties that aren't part of the default display properties, so they don't display by default.
Get-CasMailbox <identity> | format-list *
and you'll see all the available properties.