Last active
June 17, 2025 08:57
-
-
Save joerodgers/06304f41a8f8309ac12e8ebd450153ff to your computer and use it in GitHub Desktop.
Trick to force an update to the LastLogon Timestamp for an Active Directory account. This is sometimes necessary for the portal cache accounts if a companies AD team disables accounts based on the LastLogon timestamp of a user.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue | |
function Update-LastLogonTimestamp | |
{ | |
[CmdletBinding()] | |
param | |
( | |
[parameter(Position=0, Mandatory=$true)][string]$UserName | |
) | |
begin | |
{ | |
$upn = $UserName | |
$impersonationSuccessful = $true | |
} | |
process | |
{ | |
if ($UserName.IndexOf("\") -gt 0) | |
{ | |
# convert to user@domain format | |
$domain = $UserName.Split("\")[0] | |
$user = $UserName.Split("\")[1] | |
$upn = "$user@$domain" | |
} | |
try | |
{ | |
$windowsIdentity = New-Object System.Security.Principal.WindowsIdentity($upn) | |
$impersonatedContext = $windowsIdentity.Impersonate() | |
} | |
catch | |
{ | |
$impersonationSuccessful = $false | |
} | |
finally | |
{ | |
if($impersonatedContext) | |
{ | |
$impersonatedContext.Undo() | |
} | |
} | |
} | |
end | |
{ | |
$impersonationSuccessful | |
} | |
} | |
# update non-managed accounts | |
# Update-LastLogonTimestamp -UserName "portalsuperreader@contoso.com" | |
# Update-LastLogonTimestamp -UserName "portalsuperuser@contoso.com" | |
# update all managed accounts | |
Get-SPManagedAccount | % { Update-LastLogonTimestamp -UserName $_.UserName } |
Hi, i can run the script with success but the LastLogonTimestamp in AD is not getting updated.
There is an error in the code on line 30. Change $windowsIdentify.Impersonate() to $windowsIdentity.Impersonate() and it will work
@OldNGrumpy, thank you, fixed.
@caricas91, see comments above. It should be fixed now.
@joerodgers Are there any pre-reqs for this to work? I am getting the following error on the $windowsIdentity = New-Object System.Security.Principal.WindowsIdentity($upn) call:
New-Object : Exception calling ".ctor" with "1" argument(s): "A specified logon session does not exist. It may already
have been terminated.
"
At line:1 char:21
- ... sIdentity = New-Object System.Security.Principal.WindowsIdentity(" ...
-
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- CategoryInfo : InvalidOperation: (:) [New-Object], MethodInvocationException
- FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, i can run the script with success but the LastLogonTimestamp in AD is not getting updated.