Public/Get-RemoteControlStatus.ps1
<#
.SYNOPSIS Retrieves the most recent remote control and shadowing statuses for a given machine. .DESCRIPTION This function fetches the latest remote control or shadowing event from the Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational log of the specified computer within the last day. It reports on the most recent session control or shadowing activity by user. .PARAMETER machine The name or IP address of the machine for which to retrieve the event logs. .EXAMPLE Get-RemoteControlStatus -machine "Server01" This example retrieves the latest remote control status for "Server01". .NOTES Make sure that you have the appropriate permissions to access the event logs on the remote machine. #> function Get-RemoteControlStatus { param ( [Parameter(Mandatory = $true)] [string]$machine ) # Initialize dates for event log filtering $currentTime = Get-Date $thresholdTime = $currentTime.AddDays(-1) # Function to get event logs based on IDs and time function Get-EventLogs { param ([int[]]$EventIds) Get-WinEvent -ComputerName $machine -LogName 'Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational' | Where-Object { $_.Id -in $EventIds -and $_.TimeCreated -ge $thresholdTime } | Sort-Object TimeCreated -Descending | Select-Object -First 1 -Property Id, TimeCreated, @{Name='User';Expression={$_.Properties[0].Value}} } # Fetching event logs $controlEvent = Get-EventLogs -EventIds 20506, 20507 $shadowEvent = Get-EventLogs -EventIds 20503, 20504 # Prepare a timestamp for output $timestamp = Get-Date -Format "MM/dd/yyyy HH:mm:ss" # Process events and output the status if ($controlEvent -and $shadowEvent) { $timeDifference = $controlEvent.TimeCreated - $shadowEvent.TimeCreated if ($timeDifference -lt [TimeSpan]::Zero) { "$timestamp - Currently $($shadowEvent.User) is shadowing the session on $machine" } else { "$timestamp - Currently $($controlEvent.User) is controlling the session on $machine" } } elseif ($shadowEvent) { "$timestamp - Currently $($shadowEvent.User) is shadowing the session on $machine" } elseif ($controlEvent) { "$timestamp - Currently $($controlEvent.User) is controlling the session on $machine" } else { return 1 } } |