Powershell - Remote PC Report: Logon, Logoff, Lock and Unlock

I need to silently access a machine on the domain, to generate an "access" report, by date (recent to oldest) that references the following Event IDs:

7001 = 'Logon'
7002 = 'Logoff'
4800 = 'Lock'
4801 = 'UnLock'

I found the following script, however I need it amended to include 'Lock' and 'Unlock' Event IDs.

www.geekshangout.com/610-2

On the same request, I also need a copy of the XML saves as a txt files.

function get-logonhistory{
Param (
 [string]$Computer = (Read-Host Remote computer name),
 [int]$Days = 10
 )
 cls
 $Result = @()
 Write-Host "Gathering Event Logs, this can take awhile..."
 $ELogs = Get-EventLog System -Source Microsoft-Windows-WinLogon -After (Get-Date).AddDays(-$Days) -ComputerName $Computer
 If ($ELogs)
 { Write-Host "Processing..."
 ForEach ($Log in $ELogs)
 { If ($Log.InstanceId -eq 7001)
   { $ET = "Logon"
   }
   ElseIf ($Log.InstanceId -eq 7002)
   { $ET = "Logoff"
   }
   Else
   { Continue
   }
   $Result += New-Object PSObject -Property @{
    Time = $Log.TimeWritten
    'Event Type' = $ET
    User = (New-Object System.Security.Principal.SecurityIdentifier $Log.ReplacementStrings[1]).Translate([System.Security.Principal.NTAccount])
   }
 }
 $Result | Select Time,"Event Type",User | Sort Time -Descending | Format-Table

 Write-Host "Done."
 }
 Else
 { Write-Host "Problem with $Computer."
 Write-Host "If you see a 'Network Path not found' error, try starting the Remote Registry service on that computer."
 Write-Host "Or there are no logon/logoff events (XP requires auditing be turned on)"
 }
}

get-logonhistory -Computer "COMPUTERNAME" -Days "7"

Open in new window

Mike DiasAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

footechCommented:
Rather than modifying what you have above, try the below.  It's slightly modified from that found at https://community.spiceworks.com/topic/764481-get-logon-off-workstation-lock-unlock-times to include querying a remote machine.  Use of Get-WinEvent and the -FilterHashtable parameter should make this more efficient that what you had before.  You just need to modify the first two variables for your needs.
$Days = 10
$computer = "someComputer"

$events = @()
$events += Get-WinEvent -ComputerName $computer -FilterHashtable @{ 
    LogName='Security'
    Id=@(4800,4801)
    StartTime=(Get-Date).AddDays(-$Days) 
} -ErrorAction SilentlyContinue
$events += Get-WinEvent -ComputerName $computer -FilterHashtable @{ 
    LogName='System'
    Id=@(7000,7001)
    StartTime=(Get-Date).AddDays(-$Days) 
} -ErrorAction SilentlyContinue

$type_lu = @{
    7001 = 'Logon'
    7002 = 'Logoff'
    4800 = 'Lock'
    4801 = 'UnLock'
}

$ns = @{'ns'='http://schemas.microsoft.com/win/2004/08/events/event'}
$target_xpath = "//ns:Data[@Name='TargetUserName']"
$usersid_xpath = "//ns:Data[@Name='UserSid']"

If ($events) {
    $results = ForEach($event in $events) {
        $xml = $event.ToXml()
        Switch -Regex ($event.Id) {
            '4...' {
                $user = (
                    Select-Xml -Content $xml -Namespace $ns -XPath $target_xpath
                ).Node.'#text'
                Break            
            }
            '7...' {
                $sid = (
                    Select-Xml -Content $xml -Namespace $ns -XPath $usersid_xpath
                ).Node.'#text'
                $user = (
                    New-Object -TypeName 'System.Security.Principal.SecurityIdentifier' -ArgumentList $sid
                ).Translate([System.Security.Principal.NTAccount]).Value
                Break
            }
        }
        New-Object -TypeName PSObject -Property @{
            Time = $event.TimeCreated
            Id = $event.Id
            Type = $type_lu[$event.Id]
            User = $user
            Computer = $computer
        }
    }
    If ($results) {
        $results
    }
}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
footechCommented:
On the same request, I also need a copy of the XML saves as a txt files.
I really don't know what you're asking there.
0
arnoldCommented:
What is the environment?
Windows firewall settings?i
Are you running into an issue that you can not access the events log remotely?

In a domain have you looked at forwarding events from local system to a central repository on the server.
Running queries on the DCs for ....
0
Introducing the "443 Security Simplified" Podcast

This new podcast puts you inside the minds of leading white-hat hackers and security researchers. Hosts Marc Laliberte and Corey Nachreiner turn complex security concepts into easily understood and actionable insights on the latest cyber security headlines and trends.

arnoldCommented:
Rereading your.....
If your existing output is what you want/need
Using /piping through a convert to XML cmdlet

https://technet.microsoft.com/en-us/library/ff730921.aspx
0
Ajit SinghCommented:
get logon\off workstation lock\unlock times:
https://community.spiceworks.com/topic/764481-get-logon-off-workstation-lock-unlock-times

Built in and FREE Group Policy auditing. Computer Configuration > Policies > Windows Settings > Security Settings > Advanced Audit Configuration > Logon/Logoff

Configure an event forwarder: Computer Configuration > Policies > Administrative Templates > Windows Components > Event Forwarding

Audit logon/logoff/workstation lock and unlocks and more options.


Event Log Audit User Logon, Logoff and locked, unlocked:
https://www.reddit.com/r/PowerShell/comments/4pksce/event_log_audit_user_logon_logoff_and_locked/

For logoff check event 4634, workstation lock event 4800, unlock 4801. Get help from this article to audit successful Logon/Logoff and Failed Logons.

Hope this helps!
0
Mike DiasAuthor Commented:
Thanks - simple and it works.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Powershell

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.