Script Repository


User accounts disabled during a certain number of days

March 17, 2021
1514

The script creates and emails a CSV report on users disabled via Adaxes during a certain number of days.

To schedule such a report, create a scheduled task configured for the Domain-DNS object type that runs the script and assign it over any of your AD domains. To add the script to a scheduled task, use the Run a program or PowerShell script action.

Parameters:

  • $days - Specifies the number of days to include in the report.
  • $csvFilePath - Specifies a UNC path to the CSV file that will be created by the script.
  • $removeCSVFile - Specifies whether to remove the CSV file after it has been sent.
  • $to - Specifies a comma separated list of recipients of the report.
  • $subject - Specifies the email message subject.
  • $message - Specifies the email notification message.
  • $from - Specifies the e-mail address from which the message will be sent.
  • $smtpServer - Specifies the SMTP server to use when sending a notification.
Edit Remove
PowerShell
$days = 1 # TODO: modify me

# CSV file settings
$csvFilePath = "C:\Scripts\report.csv" # TODO: modify me
$removeCSVFile = $True # TODO: modify me

# E-mail settings
$to = "recipient@domain.com" # TODO: modify me
$subject = "Disabled users" # TODO: modify me
$message = "Disabled users" # TODO: modify me
$from = "noreply@domain.com" # TODO: modify me
$smtpServer = "mail.domain.com" # TODO: modify me

# Get GUIDs of all users that were disabled during the period from Adaxes log

# Bind to the directory object representing the General Log
$path = $Context.GetWellKnownContainerPath("ServiceLog")
$serviceLog = $Context.BindToObject($path)

$generalLog = $serviceLog.GeneralLog
if ($days -ne 0)
{
   $generalLog.StartDateTime = (Get-Date).AddDays(-$days)
   $generalLog.EndDateTime = Get-Date
}

# Get the log records
$log = $generalLog.Log
$records = $log.GetPage(0)

# Build filter to search for disabled users
$filter = New-Object "System.Text.StringBuilder"
[void]$filter.Append("(|")
$usersFromLog = @{}
foreach ($record in $records)
{
    if (($record.TargetObjectType -ne "user") -or ($record.TargetObjectGuid -eq $NULL))
    {
        continue
    }
    
    $operationTypes = $record.GetOperationTypes()
    if ($operationTypes -notcontains "disable account")
    {
        continue
    }
    
    # Add GUID to the filter
    $guid = [Guid]$record.TargetObjectGuid
    $guidFilter = [Softerra.Adaxes.Ldap.FilterBuilder]::Create("ObjectGuid", $guid)
    [void]$filter.Append($guidFilter)
    
    # Build report record with default values
    $reportRecord = New-Object PSObject
    $reportRecord | Add-Member -MemberType NoteProperty -Name "Name" -Value $record.TargetObjectName
    $reportRecord | Add-Member -MemberType NoteProperty -Name "Department" -Value "Cannot provide information on the user probably because the user was deleted."
    $reportRecord | Add-Member -MemberType NoteProperty -Name "Mail" -Value $NULL
    $reportRecord | Add-Member -MemberType NoteProperty -Name "Manager name" -Value $NULL
    $reportRecord | Add-Member -MemberType NoteProperty -Name "Disable datetime" -Value $record.CompletionTime
    
    if (!$usersFromLog.ContainsKey($guid))
    {
        $usersFromLog.Add($guid, (New-Object System.Collections.ArrayList))
    }
    
    $usersFromLog[$guid].Add($reportRecord)
}
[void]$filter.Append(")")

if ($usersFromLog.Count -eq 0)
{
    $Context.LogMessage("Disabled users not found. The report will not be sent", "Information")
    return
}

# Search users in AD
$searcher = $Context.BindToObject("Adaxes://rootDSE")
$searcher.SearchFilter = $filter.ToString()
$searcher.PageSize = 500
$searcher.ReferralChasing = "ADS_CHASE_REFERRALS_NEVER"
$searcher.SetPropertiesToLoad(@("name", "department", "mail", "manager", "objectGuid"))
$searcher.VirtualRoot = $True

try
{
    $searchResultIterator = $searcher.ExecuteSearch()
    $searchResults = $searchResultIterator.FetchAll()
    
    $reportRecords = @()
    foreach ($searchResult in $searchResults)
    {
        # Get user information
        $displayName = [Softerra.Adaxes.Utils.ObjectNameHelper]::GetObjectName($searchResult.AdsPath, "IncludeParentPath")
        $guid = [Guid]$searchResult.Properties["objectGuid"].Value
        $department = $searchResult.Properties["department"].Value
        $mail = $searchResult.Properties["mail"].Value
        
        # Get manager
        $managerDN = $searchResult.Properties["manager"].Value
        if ([System.String]::IsNullOrEmpty($managerDN))
        {
            $managerName = "No manager"
        }
        else
        {
            # Get manager name
            $managerPath = New-Object -TypeName "Softerra.Adaxes.Adsi.AdsPath" -ArgumentList @($null, $managerDN)
            $managerName = [Softerra.Adaxes.Utils.ObjectNameHelper]::GetObjectName($managerPath, "IncludeParentPath")
        }
        
        # Add user to report
        if ($usersFromLog.ContainsKey($guid))
        {
            $records = $usersFromLog[$guid]
            foreach ($record in $records)
            {
                $record.Name = $displayName
                $record.Department = $department
                $record.Mail = $mail
                $record."Manager name" = $managerName
                $reportRecords += $record
                $usersFromLog.Remove($guid)
            }
        }
    }
    
    # Add deleted users to report
    $reportRecords += @($usersFromLog.Values)
    
    # Save and send report
    $reportRecords | Sort-Object -Property Name | Export-csv -NoTypeInformation -Path $csvFilePath
    Send-MailMessage -To $to -from $from -SmtpServer $smtpServer -Subject $subject -Body $message -Attachments $csvFilePath
    
    if ($removeCSVFile)
    {
        # Remove temporary files
        Remove-Item $csvFilePath -Force
    }
}
finally
{
    # Release resources
    $searchResultIterator.Dispose()
}

Comments ( 0 )
No results found.
Leave a comment