I wonder if you can help me. I am trying to extract a list of recipients that have sent emails to themselves (from domain1 to domain2) using get-messagetrackinglog tool within Exchange. My little script seems to work fine with the sender's part, however after a few days of pondering I am unable to make it work with recipients. I suspect that this is because there can be many recipients (as opposed to only one sender) for each email and this requires an array to be assigned to the recipients variable however being new to powershell I am not entirely sure how to do it and how to pipe it through. The logic is the following:
a) I want to use split command to segregate all senders (using space delimiter) and fetch them into an array,
b) then to detach both sender's and recipients' first parts of addresses from domains using # delimiter and
c) compare their first part of email addresses that I've got (values returned from adam#domain1 and adam#domain2).
d) If they match - I need email message results to be exported to .csv.
I have got this far:
Get-MessageTrackingLog -server "pdnaex1" -EventID "SEND" -start "01/10/2010 00:00:00" -end "31/10/2010 23:59:59" -resultsize Unlimited | Where {[string]$.sender.split("#")[0] -like [string]$.recipients.split("#")[0]} | Select timestamp,#{Name="Sender";Expression={$.sender}},#{Name="Recipients";Expression={$.recipients}},messagesubject | export-csv X:\XXX.csv
I know above is incorrect but hope I make my question clear.
Any help is greatly appreciated. I suspect my script fails because I fail to populate an array of recipients and compare sender's value against each entry within that array but I cant work out how to do that.
You can use -like to compare an array to a scalar, but you cannot use it to compare a scalar to an array. The array argument has to come first.
PS C:> $a = "a","b","c"
PS C:> $b = "b"
PS C:> $a -like $b
b
PS C:> $b -like $a
False
You can get an arry by casting $_.recipients as [string] and splitting it on the #, but you can't select just the user part from that array easily.
Additionally, you need to reference the senders and recipients as $.sender and $.recipients, rather than $sender and $recipients.
Partially tested:
Get-MessageTrackingLog -server "pdnaex1" -EventID "SEND" -start "01/10/2010 00:00:00" -end "31/10/2010 23:59:59" -resultsize Unlimited | Where {($.recipients |% {$.split("#")[0]}) -like $_.sender.split("#")[0]} | Select timestamp,#{Name="Sender";Expression={$.sender}},#{Name="Recipients";Expression={$.recipients}},messagesubject | export-csv X:\XXX.csv
Note: the underscores after the $ don't seem to be showing up in the post in the answer.
Related
I am using Get-Mailbox to grab user/mailbox names, then Get-MailboxPermission search.
Get-Mailbox -ResultSize unlimited -Filter {name -like "a*"} | Get-MailboxPermission | where { ($_.AccessRights -eq “FullAccess, ChangePermission”) | blah blah
I have a different line for each starting letter (a*, b*, c* etc). This works fine but it seems like this could be done with some kind of loop (foreach or foreach-object) with an array reference ( #("a","b") - or it may need to be #("a*","b*") ) but I can work out the wildcard part later probably.
I don't run without a filter since there are too many mailboxes and memory usage is intense, using a letter by letter reference, the memory seems to drop back down at each letter (and running garbage collection between each letter seems to help - the output of each letter is written to a .csv).
Thought anyone - I feel I'm missing something simple since so far trying with an array is not working. The result it usually spits back ALL mailboxes vs the curated letter ones (a,b,c).
You can loop through an array to avoid the multiple lines.
$alphabet = [char[]]([int][char]'a'..[int][char]'z')
foreach ($letter in $alphabet) {
Get-Mailbox -ResultSize unlimited -Filter "name -like '$letter*'" | Get-MailboxPermission | where { ($_.AccessRights -eq “FullAccess, ChangePermission”) | blah blah
} # end foreach
This topic discusses graceful alphabet arrays.
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!
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*”}}}
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.
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.