PowerShell: List of all successful logins to the system

424 Views Asked by At

Helo,,

How can I read a list of all successful logins on the server via Powershell? The following fields should be output in the list: TimeGenerated, UserName. I'm currently stuck on the following script: I suspect that it's the Split command

Clear-Host
Get-EventLog -LogName Security | Where-Object {$_.EventID -eq 4624} | ForEach-Object {
    $message = $_.Message
    $userName = ($message -split "Kontoname: ")[1] -split "`r`n"[1]
    [PSCustomObject]@{
        TimeGenerated = $_.TimeGenerated
        UserName = $userName
    }
} | Format-Table TimeGenerated, UserName

where is my mistake, or maybe I have the wrong PowerShell command?

Who can help me or has a script example for me?

Greetings

Clear-Host
Get-EventLog -LogName Security | Where-Object {$_.EventID -eq 4624} | ForEach-Object {
    $message = $_.Message
    $userName = ($message -split "Kontoname: ")[1] -split "`r`n"[1]
    [PSCustomObject]@{
        TimeGenerated = $_.TimeGenerated
        UserName = $userName
    }
} | Format-Table TimeGenerated, UserName
1

There are 1 best solutions below

4
Santiago Squarzon On BEST ANSWER

The issue seem to be the missing of parentheses, also most likely you want the index 0 of the second split:

# This:
$userName = ($message -split "Kontoname: ")[1] -split "`r`n"[1]

# Should be:
$userName = (($message -split 'Kontoname: ')[1] -split "`r`n")[0]

However, there is a much easier way to get the Target Account Name from the 4624 events, that is by getting the value at index 5 of the .Properties property. Also note the use of Get-WinEvent (newer cmdlet) instead of Get-EventLog.

Get-WinEvent -FilterHashtable @{ LogName = 'Security'; ID = 4624 } | ForEach-Object {
    [PSCustomObject]@{
        TimeGenerated = $_.TimeCreated
        UserName      = $_.Properties[5].Value
    }
}