Link to home
Create AccountLog in
Avatar of Williams225
Williams225

asked on

Active Directory : Create a script to add users last logon date to the address field.

Experts,


I need a powershell script to add the lastlogon date for each user to the adress field in active directory. 


Can you Please help. 

 



Avatar of Amit
Amit
Flag of India image

Try this:
# Import the Active Directory module
Import-Module ActiveDirectory
 
# Get all AD users and their lastlogon date
$users = Get-ADUser -Filter * -Properties lastLogon
 
# Loop through each user and update their address field
foreach ($user in $users) {
    $address = $user.streetAddress + " " + $user.city + " " + $user.postalCode
    $address += " (Last Logon: " + $user.lastLogon.ToString("yyyy-MM-dd HH:mm:ss") + ")"
 
    Set-ADUser $user -Replace @{streetAddress=$address}
}
 
# Export updated AD users to CSV
$users | Select-Object Name, DistinguishedName, LastLogon, streetAddress, city, postalCode |
    Export-Csv -Path "C:\updated_AD_users.csv" -NoTypeInformation
Avatar of Williams225
Williams225

ASKER

Thanks Amit for your response.

Here is the error message  I get

You cannot call a method on a null-valued expression.
At C:\test.ps1:10 char:5
+     $address += " (Last Logon: " + $user.lastLogon.ToString("yyyy-MM- ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

You cannot call a method on a null-valued expression.
At C:\test.ps1:10 char:5
+     $address += " (Last Logon: " + $user.lastLogon.ToString("yyyy-MM- ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

Open in new window

That error is likely because your trying to perform a ToString on a blank value. Some AD accounts wont have a value int he last logon if they have not actually interactively logged on.
You could avoid getting ones that are blank by adding a filter to the get-aduser or add an If statement to check for blank.

Keep in mind if you have multiple DC's the lastlogon is not replicated and will only be updated on the DC that authenticates the user. lastlogontimestamp is replicated however only if the value is more than 14 days of the previous value.
I am not an expert, can you please help with the if statement?
Thanks in advance
ASKER CERTIFIED SOLUTION
Avatar of Robert
Robert
Flag of United States of America image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account