# https://www.computerperformance.co.uk/powershell/if-statement/ # http://techgenix.com/dates-in-powershell/ # https://www.computerperformance.co.uk/powershell/if-and/ # https://serverfault.com/questions/479048/remote-desktop-services-login-history # get date range from user # NOTE: might be good to get EventID we are looking for also do { $startDate = Read-Host "Enter the reports start date as dd/mm/yyyy"; $endDate = Read-Host "Enter the reports end date as dd/mm/yyyy"; $startDate = [datetime]$startDate; $endDate = [datetime]$endDate; } while ( $startDate -isnot [datetime] -And $endDate -isnot [datetime] ) # this was used when it was a static entry, but unused now #$startDate = (Get-Date -Year $year -Month $month -Day 01) #$endDate = (Get-Date -Year 2020 -Month 03 -Day 01) # name of the log to read. This contains activity on the Terminal Services $LogName = 'Microsoft-Windows-TerminalServices-LocalSessionManager/Operational' # we'll store results in this array $Results = @() # Get all events. See # https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.diagnostics/get-winevent?view=powershell-7 # for additional parameters. We might be able to speed processing with # Get-WinEvent -LogName $LogName | Where-Object { $_.TimeCreated -ge $startDate -And $_.TimeCreated -le $endDate $Events = Get-WinEvent -LogName $LogName # loop through all the events we found foreach ($Event in $Events) { # convert to xml? $EventXml = [xml]$Event.ToXML() # filter for the event.id and between the dates (inclusive) if ( $Event.Id -eq 25 -And $Event.TimeCreated -ge $startDate -And $Event.TimeCreated -le $endDate ) { # found one, so plug the stuff into a hash $ResultHash = @{ Time = $Event.TimeCreated.ToString() 'Event ID' = $Event.Id 'Desc' = ($Event.Message -split "`n")[0] Username = $EventXml.Event.UserData.EventXML.User 'Source IP' = $EventXml.Event.UserData.EventXML.Address 'Details' = $Event.Message } # then, take the result and append it to our results array $Results += (New-Object PSObject -Property $ResultHash) } } # figure out where to put the file $currentDir = $(get-location).Path; # and create a file name from the path and the start/end date $currentDir = "$currentDir" + '\RemoteDesktopUsers_' + $startDate.ToString("yyyy-MM-dd") + '_' + $endDate.ToString("yyyy-MM-dd") + '.csv'; # dump it as CSV so they can read it via a spreadsheet. $Results | Export-Csv -Path $currentDir;