Skip to content

Instantly share code, notes, and snippets.

@joerodgers
Last active June 17, 2025 08:57
Show Gist options
  • Save joerodgers/06304f41a8f8309ac12e8ebd450153ff to your computer and use it in GitHub Desktop.
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.
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 }
@caricas91
Copy link

Hi, i can run the script with success but the LastLogonTimestamp in AD is not getting updated.

@OldNGrumpy
Copy link

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

@joerodgers
Copy link
Author

@OldNGrumpy, thank you, fixed.

@joerodgers
Copy link
Author

@caricas91, see comments above. It should be fixed now.

@jay-f-evans
Copy link

jay-f-evans commented Aug 23, 2024

@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