Script Repository


Disable and update inactive users

March 25, 2021
231

The script disables users inactive for the specified period, updates one of the user properties and sends an email notification with the names of updated users. To execute the script, create a scheduled task configured for the Organizational Unit object type and add OUs users located in which should be effected by the script to the Activity Scope of the task. Make sure to add OU objects themselves, not their subtrees.

Parameters:

  • $days - Specifies the number of days a user should be inactive for to be updated by the script.
  • $propertyToUpdate - Specifies the LDAP name of the property that will be updated for inactive users.
  • $propertyValue - Specifies the description that will be set for inactive users in the specified property.
  • $pipelined - If set to $True, updating users will be passed through Adaxes pipeline to apply configured workflows (e.g. trigger corresponding business rules, create a log record in Adaxes for each update).
  • $excludedOuDNs - Specifies distinguished names (DNs) of the OUs users located in which will be ignored by the script. For information on how to obtain an object DN, have a look at the following SDK article: http://adaxes.com/sdk/HowDoI.GetDnOfObject.
  • $to - Specifies the email address of the notification recipient.
  • $subject - Specifies the email notification subject.
  • $reportHeader - Specifies the report header.
  • $noUserFoundMessage - Specifies the text that will be present in the email notification if no inactive users are found.
  • $reportFooter - Specifies the report footer.
Edit Remove
PowerShell
$days = 60 # TODO: modify me
$propertyToUpdate = "description"  # TODO: modify me
$propertyValue = "Account disabled due to inactivity for $days days." # TODO: modify me
$pipelined = $False # TODO: modify me
$excludedOuDNs = @("CN=Users,DC=domain,DC=com", "OU=Sales,DC=domain,DC=com") # TODO modify me

# E-mail settings
$to = "recipient@domain.com" # TODO: modify me
$subject = "Inactive users" # TODO: modify me
$reportHeader = "<h2>Inactive users</h2>"
$noUserFoundMessage = "No users found." # TODO: modify me
$reportFooter = "<hr /><p><i>Please do not reply to this e-mail, it has been sent to you for notification purposes only.</i></p>" # TODO: modify me

function IsDescendantOfExcludedOu ($dnObject, $excludedOuDNs)
{
    foreach ($ouDN in $excludedOuDNs)
    {
        if ($dnObject.IsDescendantOf($ouDN))
        {
            return $True
        }
    }

    return $False
}

# Build search filter
$threshold = (Get-Date).AddDays(- $days)
$thresholdInt64 = $threshold.ToFileTime()
$thresholdGeneralizedTime = [Softerra.Adaxes.Utils.Transform]::ToGeneralizedTime($threshold.ToUniversalTime())

$filterUsers = "(sAMAccountType=805306368)"
$filterCreatedBefore = "(whenCreated<=$thresholdGeneralizedTime)"

$filterNoLastLogonTimestamp = "(!(lastLogonTimestamp=*))"
$filterLoggedOnBeforeTimestamp = "(lastLogonTimestamp<=$thresholdInt64)"

$filterNoLastLogon = "(!(lastLogon=*))"
$filterLoggedOnBefore = "(lastLogon<=$thresholdInt64)"

$filterPasswordChangedBefore = "(pwdLastSet<=$thresholdInt64)"

$filter = "(&" +
    $filterUsers + $filterCreatedBefore +
    "(|" + $filterNoLastLogonTimestamp + $filterLoggedOnBeforeTimestamp + ")" +
    "(|" + $filterNoLastLogon + $filterLoggedOnBefore + ")" +
    $filterPasswordChangedBefore + ")"

# Search users
$searcher = $Context.TargetObject
$searcher.SearchFilter = $filter
$searcher.SearchScope = "ADS_SCOPE_SUBTREE"
$searcher.PageSize = 500

# Generate report
try
{
    # Execute search
    $searchIterator = $searcher.ExecuteSearch()
    $searchResults = $searchIterator.FetchAll()

    $foundedUsers = New-Object System.Text.StringBuilder
    foreach ($searchResult in $searchResults)
    {
        $dnObject = New-Object "Softerra.Adaxes.Ldap.DN" $searchResult.Properties["distinguishedName"].Value
        if (IsDescendantOfExcludedOu $dnObject $excludedOuDNs)
        {
            continue
        }

        $user = $Context.BindToObjectEx($searchResult.AdsPath, $pipelined)
        $username = $Context.GetDisplayNameFromAdsPath($searchResult.AdsPath)
        $foundedUsers.Append("<li>$username</li>")

        # Disable user
        $user.AccountDisabled = $True

        # Update user property
        $user.Put($propertyToUpdate, $propertyValue)

        # Commit changes
        $user.SetInfo()
    }
}
finally
{
    # Release resources
    if ($searchIterator) { $searchIterator.Dispose() }
}

# Build mail body
$html = New-Object System.Text.StringBuilder
$html.Append($reportHeader)
if ($foundedUsers.Length -eq 0)
{
    $html.Append($noUserFoundMessage)
}
else
{
    $html.Append("<ol>")
    $html.Append($foundedUsers.ToString())
    $html.Append("</ol>")
}
$html.Append($reportFooter)

# Send mail
$Context.SendMail($to, $subject, $NULL, $html.ToString())

Comments ( 0 )
No results found.
Leave a comment