Script Repository


Execute Custom Command on users listed in CSV file

December 07, 2016
1218

The script executes a certain Custom Command on users listed in a CSV file. The users must be contained in a certain column of the CSV file, one user account per a line. To identify them, you can use any unique property of their accounts, for example, User Logon Name or Distinguished Name.

To schedule execution of the Custom Command using the script, create a Scheduled Task configured for the Domain-DNS object type, and include any of your AD domains in the Activity Scope.

Parameters:

  • $waitTimeMilliseconds - specifies the time during which Adaxes will wait for the script to complete. It is recommended not to set a time exceeding the 10 minutes' limit applied by Adaxes to scripts executed by Business Rules, Custom Commands and Scheduled Tasks. If a script runs for more time than you specify, it will be completed, but the errors, warnings and other messages will not be added to the Execution Log. They will be sent to the e-mails identified in $recipient.
  • $commandID - specifies the ID of the Custom Command to execute. How to get the ID.
  • $csvFilePath - specifies a path to the CSV file to import.
  • $userIdentityProperty - specifies the LDAP display name of the property to identify users by.
  • $userIdentityColumn - specifies the name of the CSV file column that contains the user list.
  • $recepient - specifies a semicolon-separated list of recipients of error reports.
  • $subject - specifies the subject of emails with error reports.
  • $from - specifies the report sender.
  • $mailServer - specifies the SMTP server to be used when sending the report.
Edit Remove
PowerShell
$waitTimeMilliseconds = 9 * 60 # TODO: modify me. Time in seconds

$scriptBlock = {
    [Reflection.Assembly]::LoadWithPartialName("Softerra.Adaxes.Adsi")
    
    $commandID = "{9db88ec3-1241-4ab1-9612-c7c982baa49f}" # TODO: modify me
    $csvFilePath = "\\Server\Share\example.csv" # TODO: modify me
    $userIdentityProperty = "sAMAccountName" # TODO: modify me
    $userIdentityColumn = "Identity" # TODO: modify me
    
    # E-mail settings
    $recepient = "recipient@domain.com" # TODO: Modify me
    $subject = "Error report $date"
    $from = "noreply@domain.com" # TODO: Modify me
    $mailServer = "mail.domain.com" # TODO: Modify me
    
    Function SearchUser ($userIdentity, $propertyName, $errorReport)
    {
        # Find user in AD
        $searcher = $admService.OpenObject("Adaxes://RootDse", $NULL, $NULL, 0)
        $searcher.SearchFilter = "(&(sAMAccountType=805306368)($propertyName=$userIdentity))"
        $searcher.SearchScope = "ADS_SCOPE_SUBTREE"
        $searcher.ReferralChasing = "ADS_CHASE_REFERRALS_NEVER"
        $searcher.VirtualRoot = $True
        
        try
        {
            $searchResultIterator = $searcher.ExecuteSearch()
            $searchResults = $searchResultIterator.FetchAll()
            
            if ($searchResults.Length -eq 0)
            {
                [void]$errorReport.Append("User '$userIdentity' not found")
                [void]$errorReport.AppendLine()
                return $NULL
            }
            elseif ($searchResults.Length -gt 1)
            {
                [void]$errorReport.Append("Found more then one user with identity '$userIdentity'")
                [void]$errorReport.AppendLine()
                return $NULL
            }
            else
            {
                return $searchResults[0].AdsPath
            }
        }
        finally
        {
            # Release resources
            $searchResultIterator.Dispose()
        }
    }
    
    
    # Check whether file exists
    if (!(Test-Path -Path $csvFilePath))
    {
        Write-Error "File '$csvFilePath' was not found."
        return
    }
    
    $admNS = New-Object "Softerra.Adaxes.Adsi.AdmNamespace"
    $admService = $admNS.GetServiceDirectly("localhost")
    
    $records = Import-Csv -Path $csvFilePath
    $errorReport = New-Object "System.Text.StringBuilder"

    foreach ($record in $records)
    {
        $userPath = SearchUser $record.$userIdentityColumn $userIdentityProperty $errorReport
        
        if ([System.String]::IsNullOrEmpty($userPath))
        {
            continue
        }
        
        # Run Custom Command for the user
        $user = $admService.OpenObject($userPath, $NULL, $NULL, 0)
        $user.ExecuteCustomCommand($commandID)
    }
    
    if ($errorReport.Length -ne 0)
    {
        Send-MailMessage -to $recepient -Body $errorReport.ToString() -Subject $subject -SmtpServer $mailServer -From $from
    }
}

# Start Windows PowerShell as a separate process and run the script block in that process
$job = Start-Job -ScriptBlock $scriptBlock
Wait-Job -Job $job -Timeout $waitTimeMilliseconds

if ($job.State -ne "Completed")
{
    return
}

# Get output from external process
Receive-Job -Job $job


Comments ( 0 )
No results found.
Leave a comment