Below script will be helpful in finding the last login timestamp of the users/service accounts used by SharePoint farm. This script helps us in identifying orphan accounts which can deleted or reused elsewhere.
Logic of this script is pretty simple. Read the XML file having list of Active directory accounts. Loop through each domain controller and check and compare for the value of lastlogin with other DC. the one with the highest value is the last login timestamp value for that account. Finally the output of this is stored in a txt file.
============PowerShell Script================================================
Import-Module ActiveDirectory
$Path = "D:\Sharepoint\Lastlogintimestamp\sharepointUsers.xml"
# load it into an XML object:
$xml = New-Object -TypeName XML
$xml.Load($Path)
# note: if your XML is malformed, you will get an exception here
# always make sure your node names do not contain spaces
$rsltObj = New-Object PSObject;
$results = @();
$hostname ="";
$user =$Null;
# simply traverse the XML nodes and loop through account names:
foreach ($node in $xml.Accounts.ChildNodes)
{
$username = $node.InnerText;
write-host "Checking last login time for.... $username `n";
$dcs = Get-ADDomainController
$time = 0
foreach($dc in $dcs)
{
$hostname = $dc.HostName
$user = Get-ADUser $userName | Get-ADObject -Server $hostname -Properties lastLogon;
if( $user -ne $Null)
{
if($user.LastLogon -gt $time)
{
$time = $user.LastLogon
$hostname = $dc.HostName
}
}
}
$dt = [DateTime]::FromFileTime($time)
$rsltObj= "$username last logged on at: $dt authenticated by $hostname `n";
write-host $rsltObj;
$results += $rsltObj;
}
$results | Out-File C:\temp\SharePoint-Lastlogintimestamp.txt;
Write-host "Data saved in c:\temp\SharePoint-Lastlogintimestamp.txt";
========================================================================
===================XML File format========================================
<?xml version="1.0" encoding="UTF-8" ?>
<Accounts>
<Name>SP_Farm</Name>
<Name>SP_Service</Name>
<Name>SP_Search</Name>
</Accounts>
======================================================================
You can add more XML nodes to xml file to add more accounts which you would like to check.
No comments:
Post a Comment