Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a script configured on my GPO that tracks a certain user group their logon times exported to a csv.

Now i've gotten the question, to make it show only the LAST logon time.

At the moment it just writes down every single logon time, but they would like only the last one.

Is there a way to make it overwrite it instead?

Let's say user1 logs in 3 times, i would like to only show it the last one, and that for every user in this group.

The script i have at the moment is a very simple one:

"logon {0} {1} {2:DD-MM-YYYY HH:mm:ss}" -f (Get-Date),$env:username, $env:computername >> \serverfolderfile.csv

Much appreciated if somebody could tell me if it is possible!

question from:https://stackoverflow.com/questions/66060855/logon-time-script-how-to-overwrite-last-logon-powershell

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
317 views
Welcome To Ask or Share your Answers For Others

1 Answer

First of all, you are appending a line to a text file which is not a CSV file because the values aren't separated by a delimiter character. Then also, you use the wrong order of values for the -f Format operator: While the template string clearly has the date as the last placeholder in {2:DD-MM-YYYY HH:mm:ss}, you feed that as the first value..

Please also notice that a date format is Case-Sensitive, so you need to change DD-MM-YYYY HH:mm:ss into dd-MM-yyyy HH:mm:ss

I'd advise to change the script you now have to something like:

[PsCustomObject]@{
    User      = $env:USERNAME
    Computer  = $env:COMPUTERNAME
    LogonDate = '{0:dd-MM-yyyy HH:mm:ss}' -f (Get-Date)
} | Export-Csv -Path '\serverfolderUserLogon.csv' -NoTypeInformation -Append

Then, when it comes down to reading that file back and preserving only the latest logons, you can do

$data = Import-Csv -Path '\serverfolderUserLogon.csv' | Group-Object User | ForEach-Object {
    $_.Group | Sort-Object {[datetime]::ParseExact($_.LogonDate, 'dd-MM-yyyy HH:mm:ss', $null)} |
               Select-Object -Last 1
}

# output on screen
$data

# overwrite the CSV file to keep only the last logons
$data | Export-Csv -Path '\serverfolderUserLogon.csv' -NoTypeInformation

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...