Get-logonhistory retrieve Display name from Active directory

Hello, I’m using the script below to retrieve who has logged on and off to some servers.

In the second part of the script, I read out the file and via get-aduser I retrieve the display name of the user.

As you can see I do first a trim before, I look up the user. this part is going wrong when the hour format is longer then expected. Any idea how I can solve this?



function get-logonhistory{
Param (
[string]$Computer = (Read-Host Remote computer name),
[int]$Days = 7
$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”
{ 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])
$day=get-date -Format ddMMyy
$Result | Select Time,“Event Type”,User | Sort Time -Descending | Out-File -filepath C:\tools\Server_Specific$computer\logons$day.txt -Append
$EmailList = @( ‘’)
$From = ‘’
$Subject = “Logon History -7 days $computer”
$body = “Logon History -7 days, servers $computer”
$SMTPServer = ‘someserver.relay’

retrieve full name ########### $list = get-content -Path C:\Tools\Server_Specific\$computer\logons$day.txt | Select-Object -Skip 3 $output =foreach ( $line in $list ) { $userid = $line.substring(34).trim() (get-aduser -Identity $userid -Properties *).displayname
} $output | out-file C:\Tools\Server_Specific\$computer\logonusers$day.txt -Append


What is longer than expected? You show no example of what you get or what you expect. Is it consistently wrong? Meaning, is it always 4 digits? Help us help you…