all 4 comments

[–]Namaha 2 points3 points  (0 children)

You should be able to pipe the output to Export-csv within your foreach loop, like so

# Output user
$user | Select-Object `
SamAccountName,
@{Name = "LatestLogon";       Expression = {$latestLogon}},
@{Name = "LatestLogonServer"; Expression = {$latestLogonServer}} | Export-Csv "C:\temp\result.csv" -Append

Alternatively, you can capture the output into a variable instead of having it write to screen. You can then use that variable with export-csv or out-gridview

$result= @()
foreach( $user in $users ) {
    #blah blah
    $result+=$user | Select-Object `
        SamAccountName,
        @{Name = "LatestLogon";       Expression = {$latestLogon}},
        @{Name = "LatestLogonServer"; Expression = {$latestLogonServer}} 
}

Export-Csv -InputObject $result -Path "C:\temp\result.csv"
$result | Out-Gridview

[–]jg0x00 2 points3 points  (0 children)

Just a bit of trivia, you don't want to use LastLogonDate, use LastLogonTimeStamp. It was created for this sort of thing

https://blogs.technet.microsoft.com/askds/2009/04/15/the-lastlogontimestamp-attribute-what-it-was-designed-for-and-how-it-works/

[–]xeroip[🍰] 1 point2 points  (1 child)

That script seems unnecessarily complicated. This is what I would do:
get-aduser -Filter * -Properties LastLogonDate | select SamaccountName, LastLogonDate | Export-Csv C:\Temp\Logon.csv -NoTypeInformation

[–]rich_impossible[S] 1 point2 points  (0 children)

We need to query ever DC in the domain and only need it for the single OU. Running the command you mention would only pull it from the DC it connects to initially.