Advertisement
maximillianx

Get-TerminalSessionDetails.ps1

Sep 19th, 2014
23
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <#
  2. .LINK
  3.     Source:     http://www.spiceworks.com
  4. .SYNOPSIS
  5.     This script will query a computer for terminal server logon/logoff events, showing username, time logged, and source IP.  
  6.    
  7.     By default, the output will be written to screen, but can be emailed using the built-in parameters.
  8.  
  9. .DESCRIPTION
  10.     Checks the event logs of the specified server or servers for Terminal Server session information.
  11.  
  12. .PARAMETER After
  13.     Find results that occur after the date specified.
  14.  
  15. .PARAMETER Before
  16.     Find resuluts that occur before the date specified.
  17.  
  18. .PARAMETER ComputerName
  19.     A comma delimited list of servers (or single entry) to evaluate for RDP sessions.  If BaseDN is defined, this parameter is ignored.
  20.  
  21. .PARAMETER DomainName
  22.     The domain name you wish to search against.  If no domain name is specified, all domain results will be returned.
  23.  
  24. .PARAMETER IPAddress
  25.     The IP Address you wish to search against.  If no IP Address is specified, all IP addresses will be returned.
  26.  
  27. .PARAMETER View
  28.     Enable this switch to view the HTML report using your default .html application.
  29.  
  30. .PARAMETER MailFrom
  31.     The email address you wish this report to send from.
  32.  
  33. .PARAMETER MailTo
  34.     The email address you wish to send this report to.
  35.  
  36. .PARAMETER MailServer
  37.     The IP address or fully-qualified name of the email server to send the report through.
  38.  
  39. .PARAMETER UserName
  40.     The user name you wish to search against.  If no user name is specified, all users will be returned.
  41.  
  42. .EXAMPLE
  43.     Get-TerminalSessionDetails.ps1 -ComputerName RDSServer1
  44.  
  45.     Show the list of Remote Desktop logon/logoff events from RDSServer1 via Powershell console.
  46.  
  47. .EXAMPLE
  48.     Get-TerminalSessionDetails.ps1 -ComputerName RDSServer1
  49.  
  50.     Show all Remote Desktop logon/logoff events from server RDSServer1 in the event log.
  51.  
  52. .EXAMPLE
  53.     Get-TerminalSessionDetails.ps1 -ComputerName RDSServer1 -Before 09/01/2014 -After 08/20/2014 -UserName Rob
  54.  
  55.     Show RDSServer1 for all RDS logon/logoff activity in the event log between the dates 8/20/2014 and 09/01/2014, but only for the username 'Rob.'
  56.  
  57. .EXAMPLE
  58.     Get-TerminalSessionDetails.ps1 -ComputerName RDSServer1,RDSServer2 -UserName Rob -Domain Fabrikam
  59.  
  60.     Search the server RDSServer1 and RDSServer2 for all RDS logon/logoff activity in the event log for the username of 'Rob' who belongs to the domain 'Fabrikam.'
  61.  
  62. .EXAMPLE
  63.     Get-TerminalSessionDetails.ps1 -ComputerName RDSServer1 -MailTo rob@fabrikam.com -MailFrom TSServer_Report@fabrikam.com -MailServer 192.168.0.25
  64.    
  65.     Search the server RDSServer1 for all RDS logon/logoff activity in the event log and email the result to rob@fabrikam.com
  66.    
  67. .EXAMPLE
  68.     Get-TerminalSessionDetails.ps1 -ComputerName RDSServer1 -View
  69.  
  70.     Search the server RDSServer1 for logon/logoff events and generate HTML report (in the same folder as the script) and open your default HTML viewer when finished.
  71.  
  72. .NOTES
  73.     This script has the following prerequisites:
  74.  
  75.     Administrative rights to the remote server where you are querying event logs, specifically the 'Microsoft-Windows-TerminalServices-LocalSessionManager/Operational' log.
  76.  
  77. #>
  78. Param(
  79.     [Parameter(ValueFromPipelineByPropertyName=$true,Position=0)] [array] $ComputerName,
  80.     [DateTime] $After = (Get-Date).AddDays(-1),
  81.     [DateTime] $Before = (Get-Date).AddDays(1),
  82.     [IPAddress] $IPAddress,
  83.     [String] $Username,
  84.     [string] $DomainName,
  85.     [string] $MailFrom,
  86.     [string] $MailTo,
  87.     [string] $MailServer,
  88.     [switch] $View
  89. )
  90.  
  91. Begin{
  92.     Clear-Host
  93.     $reportemailsubject = "Terminal Server Report - $(Get-Date)"
  94.  
  95.     $Log = @()
  96.     #...................................
  97.     # Email Settings
  98.     #...................................
  99.  
  100.     $smtpsettings = @{
  101.         To =  $MailTo
  102.         From = $MailFrom
  103.         Subject = $reportemailsubject
  104.         SmtpServer = $MailServer
  105.     }
  106.     $myDir = Split-Path -Parent $MyInvocation.MyCommand.Path
  107.     $reportfile = "$myDir\RDS-ServerReport.csv"
  108.  
  109. }
  110.  
  111. Process {
  112. $Jobs = @()
  113.  
  114. ForEach ($Server in $ComputerName)
  115. {   $Jobs += Start-Job -ArgumentList $Server,$After,$Before -ScriptBlock {
  116.  
  117.         Param (
  118.             [string]$Computer,
  119.             [DateTime] $After = (Get-Date).AddDays(-1),
  120.             [DateTime] $Before = (Get-Date).AddDays(1)
  121.         )
  122.  
  123.         $IDs = @(
  124.             "21"
  125.             "24"
  126.             "25"
  127.             "23"
  128.         )
  129.         Try
  130.         {        
  131.             Get-WinEvent -computername $Computer -logname "Microsoft-Windows-TerminalServices-LocalSessionManager/Operational" | Select MachineName,Message,User,TimeCreated,SourceIP,Id | Where-Object {($IDs -contains $_.id) -and (($_.TimeCreated -gt $After) -and ($_.TimeCreated -lt $Before))}
  132.         }
  133.         Catch
  134.         {
  135.             $Error[0]
  136.             Continue
  137.         }
  138.     }
  139. }
  140.  
  141. $Jobs | Wait-Job
  142. $Data = $Jobs | Receive-Job
  143. $Jobs | Remove-Job
  144.  
  145.            $Results = Foreach ($Event in $Data) {
  146.  
  147.                 $Result = $Event | Select MachineName,Message,User,TimeCreated,SourceIP
  148.                 #If no Source IP address was specified
  149.                 $Result.TimeCreated = $Event.TimeCreated
  150.                     $ipmatch = $false
  151.                     $UserNameMatch = $false
  152.  
  153.            
  154.                 Foreach ($MsgElement in ($Event.Message -split "`n")) {
  155.                
  156.                     $Element = $MsgElement -split ":"
  157.  
  158.                     If ($Element[0] -like "User") {
  159.                         $tempUser = $Element[1].Trim(" ")
  160.                         $Result.User = $tempUser
  161.                         #$Result.User = $Element[1].Trim(" ")
  162.                         $Logon = $tempUser -split "\\"
  163.                         #$Usernamematch = $true
  164.  
  165.                         If (!$Username) {
  166.                             $UserNameMatch = $true
  167.                         }
  168.                         ElseIf ($Username -eq $Logon[1].trim()){
  169.                             $UserNameMatch = $true      
  170.                         }
  171.                         If (!$DomainName) {
  172.                             $DomainNameMatch = $true
  173.                         }
  174.                         ElseIf ($DomainName -eq $Logon[0].trim()){
  175.                             $DomainNameMatch = $true      
  176.                         }
  177.  
  178.                     }
  179.                     If ($Element[0] -like "Remote Desktop*") {$Result.Message = $Element[1].Trim(" ")}
  180.                     If ($Element[0] -like "Source Network Address"){
  181.                         If (!$IPAddress){
  182.                             $Result.SourceIP = $Element[1].Trim(" ")
  183.                             $IPMatch = $true
  184.                         }
  185.                         ElseIf ($IPAddress.ToString() -eq $Element[1].Trim(" ")){
  186.                             $Result.SourceIP = $Element[1].Trim(" ")
  187.                             $IPMatch = $true
  188.                         }
  189.                     }
  190.  
  191.                     If ($IPMatch -eq $true -and $UserNameMatch -eq $true -and $DomainNameMatch -eq $true) {
  192.                         $Log += $Result
  193.                     }
  194.  
  195.                 }
  196.  
  197.             #$Results | Select MachineName,Message,User,TimeCreated,SourceIP
  198.             }  
  199. }
  200. End {
  201.  
  202.  
  203.     If ($Log) {
  204.         $Log | Export-Csv -NoTypeInformation $reportfile -Encoding UTF8
  205.         $LogHTML = $Log | Select * | ConvertTo-Html -Fragment
  206.         $htmlhead="<html>
  207.                 <style>
  208.                 BODY{font-family: Arial; font-size: 8pt;}
  209.                 H1{font-size: 22px; font-family: 'Segoe UI Light','Segoe UI','Lucida Grande',Verdana,Arial,Helvetica,sans-serif;}
  210.                 H2{font-size: 18px; font-family: 'Segoe UI Light','Segoe UI','Lucida Grande',Verdana,Arial,Helvetica,sans-serif;}
  211.                 H3{font-size: 16px; font-family: 'Segoe UI Light','Segoe UI','Lucida Grande',Verdana,Arial,Helvetica,sans-serif;}
  212.                 TABLE{border: 1px solid black; border-collapse: collapse; font-size: 8pt;}
  213.                 TH{border: 1px solid #969595; background: #dddddd; padding: 5px; color: #000000;}
  214.                 TD{border: 1px solid #969595; padding: 5px; }
  215.                 td.pass{background: #B7EB83;}
  216.                 td.warn{background: #FFF275;}
  217.                 td.fail{background: #FF2626; color: #ffffff;}
  218.                 td.info{background: #85D4FF;}
  219.                 </style>
  220.                 <body>"
  221.  
  222.         $htmltail = "</body></html>"   
  223.         #$htmlreport = $htmlhead + $LogHTML + $htmltail
  224.  
  225.         If ($MailServer -or $MailFrom -or $MailTo) {
  226.             $htmlhead = "$htmlhead <p>Report of Remote Desktop Connections between $After and $Before. CSV version of report attached to this email.</p>"
  227.             $htmlreport = $htmlhead + $LogHTML + $htmltail
  228.  
  229.             Send-MailMessage @smtpsettings -Body $htmlreport -BodyAsHtml -Encoding ([System.Text.Encoding]::UTF8) -Attachments $reportfile
  230.         }
  231.         ElseIf ($View) {
  232.             $htmlhead = "$htmlhead <p>Report of Remote Desktop Connections between $After and $Before.</p><br>Report Run on $(Get-Date)"
  233.             $htmlreport = $htmlhead + $LogHTML + $htmltail
  234.            
  235.             $htmlreport | out-file "$myDir\RDS-ServerReport.html"
  236.             start-process "$myDir\RDS-ServerReport.html"
  237.         }
  238.         Else {
  239.             $Log
  240.         }
  241.  
  242.     }
  243.     Else {
  244.         Write-Output "No results found"
  245.     }
  246. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement