Get-MessageTracking logs for multiple users - powershell

We've been given a task to get stats on whether 6000+ Contacts have been used in the last 30 days.
We're on Exchange 2013 CU9
So obviously
$ht = Get-TransportService *EXC*
$ht | Get-MessageTrackingLog -Recipients user#domain.com -EventId send
So I'm writing a function to allow us to put single addresses into the above and if we want also feed in a list or CSV. that's easy enough.
But with over 6000 to search on, and 32 Transport servers with 30 day so of logs this is going to take an incredibly long time.
Just wondering if anyone had seen this issue before and come up with a way of speeding things up?
Thanks in advance.

You would be better just to collect the raw logs and parse those with the Log Parser studio https://gallery.technet.microsoft.com/office/Log-Parser-Studio-cd458765 which will perform much better.

Related

Powershell Exchange Online email counting report

I'm trying to work on some monthly statistics for our company, where I could set a schedule task with powershell to get this data monthly. First of all, I would like to extract the total number of emails (received and sent) over the last 30 days.
I've been looking at the ExchangeOnlineManagement Module, and from what I can see, I would need to use the "Start-HistoricalSearch" to be able to retrieve emails. But I don't want to create a CSV of all emails, I just want as a result the total number of emails, but I can't seem to be able to do something like.
Has anyone had the same need or can help me understand how can I reach this goal?
Thanks

Active Directory transient error when bulk using ActiveDirectory cmdlet

I have a system which synchronizes users from a data source. The data source consists of user information. When a new user is synchronized, a PowerShell task is triggered which creates or updates the user. This is all fine but when the amount of new/updated users becomes too big, some of the tasks fail with some interesting errors such as:
"The server has returned the following error: invalid enumeration
context."
or
"A connection to the directory on which to process the request was
unavailable. This is likely a transient condition."
When troubleshooting it seems obvious that the reason these errors occur are a lack of resources. It is because all the simultaneously triggered tasks are importing the module on their own PS session.
So I went trying some different things and measuring Import-Module speed etc. So I've concluded that it is faster to run Import-Module and then Get-ADUser for instance, then just Get-ADUser (which would also import the module).
Measure-Command {Import-Module ActiveDirectory}
Average time 340 ms
Measure-Command {Get-ADUser -Filter *}
Average time 420 ms
Get-ADUser after the module is imported
Average time 10 ms
But these marginal differences are not going to do anything to the issue. So I had to look further. I find that disabling the drive might help speed up the process, so I've added the following before importing the module:
$Env:ADPS_LoadDefaultDrive = 0
Measure-Command {Import-Module ActiveDirectory}
Average time 85 ms
4 times faster! But still the error persists at high amounts of users at the same time (e.g. 50 tasks). So I thought about polling the availability in the script, or make a do..while loop. Or maybe the system which fires the separate tasks needs to be redesigned, to have some sort of queue.
Does anyone recognize this situation? Or have some thoughts they'd like to share on this subject?
It is because all the simultaneously triggered tasks are importing the module on their own PS session.
Then you need to make sure this doesn't happen, or at least not so much that you run out of resources. So you have two options:
Limit the number of tasks that get run at any one time (maybe 5 at a time).
Make it one task that can work on several accounts. This way the module only gets loaded once.
I think option 2 is the better solution. For example, rather than triggering the script right away, your synchronization job could just write the username to a file (or in memory even) and once it's done finding all the users, it triggers the PowerShell script and passes the list (or the script could read the file that was written to). You have options there - whatever works best.
Update: All of .NET is available in PowerShell, so another option is to change the whole script to use .NET's DirectoryEntry instead of the ActiveDirectory module, which would use much less memory. There are even shortcuts for it in PowerShell. For example, [ADSI]"LDAP://$distinguishedName" would create a DirectoryEntry object for a user. It is a substantial rewrite, but the performance is much better (speed and memory consumption).
Here are some examples of searching with DirectorySearcher (using the [ADSISearcher] shortcut): https://blogs.technet.microsoft.com/heyscriptingguy/2010/08/23/use-the-directorysearcher-net-class-and-powershell-to-search-active-directory/
And here's an example of creating accounts with DirectoryEntry: https://www.petri.com/creating-active-directory-user-accounts-adsi-powershell

PS Active Directory per user login count

I've been looking for a solution but cannot find anything easy enough or reliable, so please excuse for bringing this up again.
In a typical AD environment, what I want to get is a monitoring report that would say something in the lines that "user X has logged in YYYY times in the past ZZ period".
The lastlogon date on get-aduser in PS is the only thing I can find, as that changes with each login, but cannot be easily scripted in a scheduled run to generate a report for eg.
Has anyone implemented this or use any tools that can track this?
There's only one reliable way to do what you want: collect and parse the audit logs from all Domain Controllers.
If you have a few users that you want to keep track of over time, an alternative could be monitoring the sum of the logonCount values for that user. Since the logonCount attribute is not replicated, you will have to collect it from each DC per user, then calculate the difference.
You can probably check the AD replication logs for replication of changes to the lastlogontimestamp property.
This script will do what you want for a particular user - closest I've managed to come so far.

Powershell launch at specific times

I am building a system to restart computers for patch purposes. Most of the skeleton is there and working, I use workflows and some functions to allow me to capture errors and reboot the systems in a number of ways in case of failures.
One thing I am not sure of is how to set up the timing. I am working on a web interface where people can schedule their reboots, either dynamic (one-time) or regularly scheduled (monthly). The server info and times for the boots is stored in a SQL database.
The part that I am missing is how to trigger the reboots when scheduled. All I can think of is allowing for whole hour increments, and run a script hourly checking to see if any servers in the db have a reboot time that "matches" the current time. This will likely work, but is somewhat inflexible.
Can anyone think of a better way? Some sort of daemon?
For instance, user X has 300 servers assigned to him. He wants 200 rebooted at 10 PM on each Friday, and 50 once a month on Saturday at 11 PM. There will be over a dozen users rebooting 3000-4000 computers, sometimes multiple times monthly.
Ok, let's say you have a script that takes a date and time as an argument that will look up what computers to reboot based on that specific date and time, or schedule, or whatever it is that you're storing in your sql db that specifies how often to reboot things. For the sake of me not really knowing sql that well, we'll pretend that this is functional (would require the PowerShell Community Extensions snapin for Invoke-AdoCommand cmdlet):
[cmdletbinding()]
Param([string]$RebootTime)
$ConStr = 'Data Source=SQLSrv01;Database=RebootTracking;Integrated Security=true;'
$Query = "Select * from Table1 Where Schedule = $RebootTime"
$Data = Invoke-AdoCommand -ProviderName SqlClient -ConnectionString $ConStr -CommandText $Query
$data | ForEach{Do things to shutdown $_.ServerName}
You said you already have things setup to reboot the servers so I didn't even really try there. Then all you have to do is setup a scheduledjob for whenever any server is supposed to be rebooted:
Register-ScheduledJob –FilePath \\Srv01\Scripts\RebootServers.ps1 –Trigger #{Frequency=Weekly; At="10:00PM"; DaysOfWeek="Saturday"; Interval=4} -ArgumentList #{'RebootTime'="Day=Saturday;Weeks=4;Time=22:00"}
That's an example, but you know, you could probably work with it to accomplish your needs. That will run it once every 4 Saturdays (about monthly). That one scheduled task will query the sql server to match up a string against a field, and really you could format that any way you want to make it as specific or general as desired for the match. That way one task could reboot those 200 servers, and another could reboot the other 50 all dependent on the user's desires.

Exchange mailbox traffic auditing?

I´m interested in getting a specific users mailbox statistics in Exchange 2010. The purpose is to gather details about a support mailbox and the support team performance.
In my case I'd like to try and get the:
number of received and sent mails last 24 hrs
number of mails added to subfolder last 24 hrs
average time emails spend in Inbox
average time emails spend being unread
I know how to get the first part of #2 and export it to a file based on the current date, but have no idea how to limit the time frame to the last 24 hrs:
$date = (Get-Date).toString(‘yyyy-MM-dd’)
Get-MailboxFolderStatistics "username" | sort-object itemsinfolder -descending | ft Folder, FolderPath, ItemsInFolder, FolderSize -auto | export-csv -path $date.csv
Some statistics might not be supported, but I'd very much like some help with what is possible.
I don't believe you're going to get all the stats you're wanting with get-mailboxstatistics. You're going to have to go into that mailbox and start examining emails.
I'd start with Glen Scales blog:
http://gsexdev.blogspot.com/
and research usint the EWS managed API with Powershell. The "Modified" property on an email should reflect the last time it was moved within the mailbox. You can determine which emails have or haven't been read from the item properties, but I don't know of a property that records when they were read so you may need to run the script periodically to monitor for which ones have been read since the last time it checked.