PowerShell: How To Receive Alerts When A Box is RDP’d

The following PowerShell script sends a text message and e-mail whenever any user RDPs into a Windows machine (obviously you would only want to do this in limited, critical instances).  

This script is a bit of a work in progress, but got the job done for our purposes.  Note, much of this code, and the directions for its application, were inspired by https://pingforinfo.com/receive-e-mail-alert-on-rdp-login-at-windows-servers/.

  1. Drop the following script somewhere on your system, such as c:\scripts\
  2. Launch “Event Viewer” and find the latest event on successful RDP login. It should be located under “Applications and Services logs/Microsoft/Windows/TerminalServices-LocalSessionManager/Operational” with Event ID 21. Once found, right-click on the event and select “Attach Task to This Event…” then use the default options for the first couple screens of the wizard.
  3. Create a task to “Start a Program” with the following parameters:
    1. Program/script: PowerShell.exe
    2. Arguments: c:\scripts\Get-RDPUser.ps1.
  4. Once saved you should start receiving alerts whenever someone RDPs into your system.
            $SMTPServer = "smtp.colostate.edu"
$SMTPPort = "587"
$Username = "sgeisert@colostate.edu"
$Password = "passhere"
$to = "shaun.geisert@colostate.edu"
$cc = "verizon_number@vtext.com"
RDetails = @()

$a = "<style>"
$a = $a + "TABLE{border-width: 1px;border-style: solid;border-color:black;}"
$a = $a + "Table{background-color:#ffffff;border-collapse: collapse;}"
$a = $a + "TH{border-width:1px;padding:0px;border-style:solid;border-color:black;}"
$a = $a + "TR{border-width:1px;padding-left:5px;border-style:solid;border-color:black;}"
$a = $a + "TD{border-width:1px;padding-left:5px;border-style:solid;border-color:black;}"
$a = $a + "</style>"

$Computer = hostname 
$LogOnEvents = Get-WinEvent -filterHashtable @{LogName='Security'; Id=4624; Level=0} | Where-Object{ $_.Properties[8].Value -eq 10} | select -First 1

$HashProps = @{
UserName = $LogOnEvents.Properties[5].value
ClientIP = $LogOnEvents.Properties[18].value
LogonTime = $LogOnEvents.TimeCreated
$USERDetails = New-Object -TypeName PSCustomObject -Property $HashProps |
Select-Object -Property UserName,ClientIP,LogonTime
$User = $USERDetails | Select -ExpandProperty UserName

# assemble message
$message = New-Object System.Net.Mail.MailMessage
$message.subject = "[RDP Event] User $User logged in to $Computer"
$message.body = Body = ( $USERDetails | ConvertTo-Html -Head $a | Out-String -Width ([int]::MaxValue))
$message.from = $username

$smtp = New-Object System.Net.Mail.SmtpClient($SMTPServer, $SMTPPort);
$smtp.EnableSSL = $true
$smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password);

write-host “Mail Sent”