Script loginhistorik användare (aktuell säkerhetslogg).

Script för att söka genom säkerhetsloggar efter EventID 4624 och en specifik användare.
Skriver ut resultat till skärm och CSV fil.
Kör lokalt om möjlighet finns (remote tar lååång tid..)
#--------------------------------------------------------
# Script to view loginhistory for a user (Eventid 4624)
# Parameters get-logon -username -computer
#
#-------------------------------------------------------

param (
[string]$Computer = $env:COMPUTERNAME,
[Parameter(Mandatory=$true)][string]$username
)
#Variables
$Scriptpath = Split-Path -Parent $MyInvocation.MyCommand.Path
$Logdate = get-date -format "yyMMdd-hhmmss"
$csvfile = "$scriptpath\Login $username $computer $Logdate.log"
$ErrorActionPreference = "Stop"

# Get Events from Securitylogs with ID 4624 and $username..
# Break if RPC error

Write-Host "Gathering Events, this can take awhile..." -ForegroundColor Green
Try
{
$Events = Get-winevent -computer $Computer -FilterHashtable @{logname='Security';ID="4624"} | where {$_.message -match "Account Name:\s*$username"}
}
catch [System.Diagnostics.Eventing.Reader.EventLogException]
{
write-host "The RPC server on $computer is not available, check firewallsettings" -ForegroundColor Red
break
}

# Parse out the event message data
ForEach ($Event in $Events) {
# Convert the event to XML
$eventXML = [xml]$Event.ToXml()
# Iterate through each one of the XML message properties
For ($i=0; $i -lt $eventXML.Event.EventData.Data.Count; $i++) {
# Append these as object properties
Add-Member -InputObject $Event -MemberType NoteProperty -Force -Name $eventXML.Event.EventData.Data[$i].name -Value $eventXML.Event.EventData.Data[$i].'#text'
}
}

# Write output
$Events | select @{ name = "Computer" ; Expression = {$_.MachineName}}, @{ Name = "Logontime" ; expression = {$_.TimeCreated }},targetdomainname,targetusername,@{ Name= "LogonFromIP" ; Expression = { $_.ipaddress}} | Out-GridView
$Events | select @{ name = "Computer" ; Expression = {$_.MachineName}}, @{ Name = "Logontime" ; expression = {$_.TimeCreated }},targetdomainname,targetusername,@{ Name= "LogonFromIP" ; Expression = { $_.ipaddress}} | Export-Csv -NoTypeInformation -Encoding UTF8 $csvfile