Search code examples
powershellpowershell-4.0

Remote Desktop Services login history for specific user


I found a script here: https://serverfault.com/questions/479048/remote-desktop-services-login-history

Here is the script:

Get-Eventlog -LogName Security | where {$_.EventId -eq "4624"} | select-object @{Name="User"
;Expression={$_.ReplacementStrings[5]}}  | sort-object User -unique |ogv

The goal is to search for a specific user and see when was the last time that he have login to the terminal server, and with that script, i'am unable to make it to show the date too, only the user name, I've tried to add some property after running get-member, but didn't got any success

thank you for your help


Solution

  • You can use the Get-WinEvent cmdlet for this like below:

    $user = 'The SamAccountName of the user you want to track'
    
    Get-WinEvent -FilterHashtable @{LogName='Security';ID=4624} -MaxEvents 100 | 
        Where-Object {$_.Properties[5].Value -eq $user } |
        Select-Object -Property @{Name = 'UserName'; Expression = { $_.Properties[5].Value }}, 
                                @{Name = 'LogonTime'; Expression = { $_.TimeCreated }},
                                MachineName | 
        Out-GridView
    
    # $_.Properties[5].Value --> TargetUserName
    

    The -MaxEvents 100 is just an example. Change that value or remove the parameter alltogether if you need to


    To retrieve only 3events, use the -MaxEvents parameter with value 3. You can also select the (last) 3 events afterwards if that is what you want by appending -Last 3 to the Select-Object command.

    To see what the Properties array contains for this event ID, you can do

    $props = (Get-WinEvent -MaxEvents 1 -FilterHashtable @{LogName='Security';ID=4624}).Properties
    for ($i = 0; $i -lt $props.Count; $i++) {
        "Properties[$i].Value --> {0}" -f $props[$i].Value
    }
    

    Comparing this to what you can read in the XML-view of eventvwr.exe:

    SubjectUserSid            = 0
    SubjectUserName           = 1
    SubjectDomainName         = 2
    SubjectLogonId            = 3
    TargetUserSid             = 4
    TargetUserName            = 5
    TargetDomainName          = 6
    TargetLogonId             = 7
    LogonType                 = 8
    LogonProcessName          = 9
    AuthenticationPackageName = 10
    WorkstationName           = 11
    LogonGuid                 = 12
    TransmittedServices       = 13
    LmPackageName             = 14
    KeyLength                 = 15
    ProcessId                 = 16
    ProcessName               = 17
    IpAddress                 = 18
    IpPort                    = 19
    

    These values differ when asking for other events and are only valid for LogName='Security';ID=4624