Script Repository


Enabled users

August 10, 2018
1292

The script creates and emails a CSV report containing enabled users from all AD domains managed by Adaxes.

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:

  • $scope - specifies the Distinguished Name (DN) of the AD container or OU where the users are located. You can set the parameter to $NULL in order to include all objects in all AD domains managed by Adaxes. You can also use %distinguishedName% as scope to include only users in the AD domain on which the script is executed;
  • $propertiesToExport - specifies the properties of the user accounts to export. each property must be specified in the following format: @("propertyLdapName", "Property Display Name"), where:
    • propertyLdapName - specifies the LDAP display name of the property you need;
    • Property Display Name - specifies a display name under which the property will appear in the CSV file;
  • $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;
  • $sortColumns - specifies the columns to sort by;
  • $sortDirection - specifies the sort direction;
  • $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 notification sender;
  • $smtpServer - specifies the SMTP server to use when sending a notification.
Edit Remove
PowerShell
$scope = "%distinguishedName%" # TODO: modify me. if $NULL - search in all domains
$propertiesToExport = @(
    @("name", "Name"),
    @("distinguishedName", "Parent OU"),
    @("description", "Description"),
    @("department", "Department"),
    @("division", "Division"),
    @("mail", "Email"),
    @("givenName", "First Name"),
    @("sn", "Last Name"),
    @("sAMAccountName", "Logon Name"),
    @("manager", "Manager"),
    @("physicalDeliveryOfficeName", "Office"),
    @("title", "Job Title"),
    @("lastLogonTimestamp", "Last Logon"),
    @("employeeID", "Employee ID"),
    @("userAccountControl", "Account Options")
) # TODO: modify me

# CSV file settings
$csvFilePath = "C:\scripts\report.csv" # TODO: modify me
$removeCSVFile = $True # TODO: modify me
$sortColumns = @("Parent OU", "Last Logon") # TODO: modify me
$sortDirection = "Ascending" # TODO: modify me: Descending or Ascending

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

$accountOptions = @{
    1 = "Logon script is executed";
    2 = "Account is disabled";
    8 = "Home directory is required";
    16 = "Account is locked out";
    32 = "No password is required";
    64 = "User cannot change password";
    128 = "Store password using reversible encryption";
    256 = "Temporary duplicated account";
    512 = "Normal account";
    2048 = "Interdomain trust account";
    4096 = "Workstation trust account";
    8192 = "Server trust account";
    65536 = "Password never expires";
    131072 = "MNS logon account";
    262144 = "Smart card is required for interactive logon";
    524288 = "Account is trusted for delegation";
    1048576 = "Account is sensitive and cannot be delegated";
    2097152 = "Use Kerberos DES encryption types for this account";
    4194304 = "Do not require Kerberos preauthentication";
    8388608 = "Password has expired";
    16777216 = "Account is trusted to authenticate for delegation"
}

function GetObjectDisplayName($objectDN)
{
    $objectPath = New-Object -TypeName "Softerra.Adaxes.Adsi.AdsPath" -ArgumentList @($null, $objectDN)
    return [Softerra.Adaxes.Utils.ObjectNameHelper]::GetObjectName($objectPath, "IncludeParentPath")
}

function BuildReport($searhFilter, $propertiesToExport, $scope)
{
    # Get display names for the properties
    $propertyLdapNames = @()
    $propertyFriendlyNames = @()
    foreach ($propertyInfo in $propertiesToExport)
    {
        $propertyLdapNames += $propertyInfo[0]
        $propertyFriendlyNames += $propertyInfo[1]
    }
    
    # Find users
    if ([System.String]::IsNullOrEmpty($scope))
    {
        $searcher = $Context.BindToObject("Adaxes://rootDSE")
        $searcher.VirtualRoot = $True
    }
    else
    {
        $searcher = $Context.BindToObjectByDN($scope)
    }
    $searcher.SearchFilter = $searhFilter
    $searcher.PageSize = 500
    $searcher.SearchScope = "ADS_SCOPE_SUBTREE"
    $searcher.SetPropertiesToLoad($propertyLdapNames)
    
    try
    {
        $searchResultIterator = $searcher.ExecuteSearch()
        $searchResults = $searchResultIterator.FetchAll()
        
        # Build report
        $report = @()
        foreach ($searchResult in $searchResults)
        {                        
            # Get property values for each user
            $record = New-Object PSObject
            for ($i = 0; $i -lt $propertyLdapNames.Length; $i++)
            {
                $propertyName = $propertyLdapNames[$i]
                
                # Get property value
                $value = $searchResult.Properties[$propertyName].Value
                switch ($propertyName)
                {
                    "distinguishedName"
                    {
                        # Get parent object display name
                        $userDN = New-Object "Softerra.Adaxes.Ldap.DN" $value
                        $value = GetObjectDisplayName $userDN.Parent
                    }
                    "manager"
                    {
                        # Get manager display name
                        if ($value -ne $NULL)
                        {
                            $value = GetObjectDisplayName $value
                        }
                    }
                    "lastLogonTimestamp"
                    {
                        if (($value -eq 0) -or ($value -eq $NULL))
                        {
                            $value = $NULL
                        }
                        else
                        {
                            try
                            {
                                $value = [DateTime]::FromFiletime([Int64]::Parse($value))
                            }
                            catch
                            {
                                $Context.LogMessage("Cannot convert value '$value' to the date/time format", "Warning") # TODO: modify me
                                $value = $NULL
                            }
                        }
                    }
                    "userAccountControl"
                    {
                        $userAccountControl = @()
                        foreach ($key in $accountOptions.Keys)
                        {
                            if ($value -band $key)
                            {
                                $userAccountControl += $accountOptions[$key]
                            }
                        }
                        $value = $userAccountControl -join ";"
                    }
                }
                
                $record | Add-Member -MemberType NoteProperty -Name $propertyFriendlyNames[$i] -Value $value
            }
            $report += $record
        }
        return ,$report
    }
    finally
    {
        # Release resources used by the search
        $searchResultIterator.Dispose()
    }
}

# Build CSV report
$csvReport = @()

# Build filter: enabled and not expired users
$currentDate = (Get-Date).ToFileTime()
$filter = "(&(sAMAccountType=805306368)(!(userAccountControl:1.2.840.113556.1.4.803:=2))(|(accountExpires>=$currentDate)(accountExpires=0)(accountExpires=9223372036854775807)))"

# Generate report
$csvReport += BuildReport $filter $propertiesToExport $scope

# Export to CSV
if ($sortDirection -eq "Descending")
{
    $sortParameters = @{
        "Property" = $sortColumns;
        "Descending" = $NULL;
    }
}
else
{
    $sortParameters = @{
        "Property" = $sortColumns;
    }
}

# Export to CSV
$csvReport | Sort-Object @sortParameters | Export-csv -NoTypeInformation -Path $csvFilePath

# Send mail
Send-MailMessage -To $to -from $from -SmtpServer $smtpServer -Subject $subject -Body $message -Attachments $csvFilePath

if ($removeCSVFile)
{
    # Remove temporary file
    Remove-Item $csvFilePath -Force
}

Comments ( 0 )
No results found.
Leave a comment