How to export last logon to *.csv

Hi guys,

I have this script:

$LastLogonDate= (Get-Date).AddDays(-180)
Get-ADUser -Properties LastLogonTimeStamp -Filter {LastLogonTimeStamp -lt $LastLogonDate } | ?{$_.Enabled –eq $True} |  Sort LastLogonTimeStamp| FT Name, @{N='lastlogontimestamp'; E={[DateTime]::FromFileTime($_.lastlogontimestamp) | Export-csv -path c:\AD\Reports\Inactive_users.csv -Append -Encoding UTF8}} -AutoSize

It works just for an half part so I can export to the *.csv file just “lastlogontimestamp” and the “name” column is showed on the screen but is not inserted in to the file… maybe I should move “Export-csv” somewhere but I didn’t understand where… :frowning:

GabrieleMax

Gabriele,
Welcome to the forum. :wave:t4:

Using aliasses in scripts or in forums is considered very bad style. Please avoid them. And it would make your code much easier to read if you used line breaks after each pipe.

Format cmldets like Format-Table or Format-List are meant to be used to format console output only and should always be the last element of a pipeline. It does not make sense to pipe the output of a format cmdlet further down the pipeline.

Something like this should work:

$LastLogonDate= (Get-Date).AddDays(-180)
Get-ADUser -Filter {LastLogonTimeStamp -lt $LastLogonDate } -Properties LastLogonTimeStamp | 
    Where-Object {$_.Enabled} | 
    Sort-Object LastLogonTimeStamp | 
    Select-Object Name, @{Name = 'lastlogontimestamp'; Expression = {[DateTime]::FromFileTime($_.lastlogontimestamp)}} | 
        Export-csv -Path c:\AD\Reports\Inactive_users.csv -Encoding UTF8 -NoTypeInformation

Here is some more useful stuff to read to improve your code

2 Likes

Hi Olaf,

thank you for your quick reply! :slight_smile:

I didn’t know how to show my code, I understood it was quite wrong to show it in that mode but I didn’t know how to do it better than it, thanks for your informations! :slight_smile:

The script works fine, thanks to help me for this and thanks for the link to improve the code! :slight_smile:

Have a nice day!
GabrieleMax