Home > Blockchain >  Powershell - ActiveDirectory Find LastLogon and Manager for all users in OU
Powershell - ActiveDirectory Find LastLogon and Manager for all users in OU

Time:09-30

I would like to get LastLogon in a human readable form for all users in an OU and also their manager. Generally people will Logon to the local Domain Controller Server - so if I could limit to checking just the local one DCLocal would be fine.

So I have this (note I have TimeStamp - I don't want this as it is too far out of possible compliance - I need to be accurate within 1 day not 14 and not 19 but 1 day.

Get-ADUser -Filter {enabled -eq $true} -SearchBase "OU=STAFF,OU=MINE,DC=mine,DC=local" 
-ResultPageSize 0 -Prop CN,lastLogonTimestamp | Select CN,@{n="lastLogonTimeStamp";e=
{[datetime]::FromFileTime($_.lastLogonTimestamp)}} | Export-CSV -NoType c:\temp\lastLogin.csv

I am having trouble figuring out how to do this , I have looked at this PowerShell Script to Return Employee's Manager and their Manager (x5) I am not sure how to integrate that with what I have.

How can I do both of these functions [LastLogon and Manager] and limit the domain controllers to the local box and OU's as I have in my example code.

Following Abraham's advice below I have tried

Get-ADUser -Filter {enabled -eq $true} -Server MYLDC01 
-SearchBase "OU=STAFF,OU=MINE,DC=mine,DC=local" 
-ResultPageSize 0 -Prop CN,LastLogon, Manager | Select 
CN,@{n="LastLogon";e={[datetime]::FromFileTime($_.LastLogon)}
, Manager} | Export-CSV -NoType c:\temp\lastLogon.csv

Which results in

Missing expression after ','.
At line:1 char:238
  ... astLogon";e={[datetime]::FromFileTime($_.LastLogon)}, Manager} | Expo ...
    

                                                    ~~~~~~~
Unexpected token 'Manager' in expression or statement.

CodePudding user response:

Caveat: The only way to ascertain the actual last logon time is to query EVERY domain controller, though it will be somewhat right if you have every subnet properly configured along with its local Domain Controller in AD Sites and Services so that the user's logon DC should be the local one.

I have a script which querys the DC logs and finds exact logon time and the machine they used but it does obviously take a LONG time to run so is used in troubleshooting single users rather than run regularly.

That said - you must also be careful when copy-pasting code from the web that you grab only what you need, espcially if it's a snippet of a larger script - unexpected line breaks and brackets in the incorrect places will render the script useless:

Compare this with your pasted code and keep it on a single line - it should work ok as far as it goes:

Get-ADUser -Filter {enabled -eq $true} -Server MyDC -SearchBase "OU=TheseUsers,OU=MyUsers,DC=my,DC=local" -ResultPageSize 0 -Prop CN,LastLogon, Manager | Select CN,@{n="LastLogon";e={[datetime]::FromFileTime($_.LastLogon)}}, Manager
  • Related