コード例 #1
0
def getParametersAsText(indexesForCatalogPath=[]):
    """ Get a list of all arcpy parameters as text.

        **Description:**
        
        Uses `arcpy.GetParameterAsText`_ to assemble a list of strings representing parameters from the script that is 
        being executed. ie. the input parameters for an ArcGIS toolbox dialog box, an ArcGIS modelbuilder model, or
        another python script, etc.
        
        The optional *indexesForCatalogPath* argument allows you to indicate which indexes must have
        the full catalog path retrieved. For example, if the layer name is the text returned for the parameter, you can 
        request the full path of the dataset for that parameter by adding its index to a list passed to this function. 
        
        This seems to be most critical for input parameters - the code produces an error for output parameters, so 
        don't include them in the list of integer indexes       
        
        **Arguments:**
        
        * *indexesForCatalogPath* - Iterable with integer indexes of parameters to get a catalog path for.
        
        
        **Returns:** 
        
        * list of strings
    
    """

    textParameters = []
    total = arcpy.GetArgumentCount()
    for count in range(0, total):
        try:
            if count in indexesForCatalogPath:
                #                if hasattr(arcpy.GetParameter(count), "value"):
                #                    arcpy.AddMessage("Parameter {0} has value attibute".format(count))
                #                else:
                #                    arcpy.AddMessage("Parameter {0} has NO value attibute".format(count))

                # check if input parameter is a lyr file with arcpy.Exists
                if arcpy.Exists(arcpy.GetParameter(count)):
                    parameterAsText = arcpy.Describe(
                        arcpy.GetParameter(count)).catalogPath.strip("'")
                else:
                    parameterAsText = arcpy.Describe(
                        arcpy.GetParameter(
                            count).dataSource).catalogPath.strip("'")
            else:
                parameterAsText = arcpy.GetParameterAsText(count).strip("'")

            textParameters.append(parameterAsText)
        except:
            # We're going to make an assumption that something went wrong with getting parameters, and to preserve
            # the argument index, add an ESRI null "#".
            textParameters.append("#")

    return textParameters
コード例 #2
0
def main():

    try:
        # Get the input parameters to this tool
        if arcpy.GetArgumentCount() != 3:
            raise Exception("Incorrect number of arguments")

        outputJxlFile = arcpy.GetParameterAsText(0)
        mxdDir = arcpy.GetParameterAsText(1)
        tawDir = arcpy.GetParameterAsText(2)

        # Get any necessary licenses before importing the toolbox
        checkOutLicenses("", ["JTX"])

        # Import the Workflow Manager toolbox
        wmxToolbox = getWorkflowManagerToolboxLocation()
        arcpy.ImportToolbox(wmxToolbox, "WMXAdminUtils")

        # Identify all of the MXD files
        #
        # TODO: Move this code into an "Upload All Map Documents" script?
        fileList = os.listdir(mxdDir)
        mxdFiles = []
        for f in fileList:
            (unused, ext) = os.path.splitext(f)
            if ext.lower() == ".mxd":
                mxdFiles.append(mxdDir + os.sep + f)

        # Upload all of the MXDs to the DB
        mxdCategory = "#"
        mxdDescription = "#"
        overwriteMxds = "OVERWRITE"
        for mxd in mxdFiles:
            temp = os.path.basename(mxd)
            (targetName, unused) = os.path.splitext(temp)
            arcpy.UploadMapDocument_WMXAdminUtils(mxd, targetName, mxdCategory,
                                                  mxdDescription,
                                                  overwriteMxds)
            logPreviousToolMessages()

        # Upload all of the Task Assistant workbooks to the DB
        arcpy.UploadAllTaskAssistantWorkbooks_WMXAdminUtils(tawDir, "true")
        logPreviousToolMessages()

        # Back up the database to the specified JXL file
        prettyPrint = "PRETTY_PRINT"
        arcpy.BackupWorkflowManagerDatabase_WMXAdminUtils(
            outputJxlFile, prettyPrint)
        logPreviousToolMessages()

    except Exception, ex:
        printUsage()
        arcpy.AddError("Caught exception: " + str(ex))
コード例 #3
0
def main():

    try:
        arcpy.env.overwriteOutput = True

        # Get the input parameters to this tool
        if arcpy.GetArgumentCount() != 1:
            raise Exception("Incorrect number of arguments")
        excelWorksheetName = os.path.abspath(arcpy.GetParameterAsText(0))

        # Get any necessary licenses before importing the toolbox
        checkOutLicenses("", ["JTX"])

        # Import the Workflow Manager toolbox
        wmxDevUtilsToolbox = getWorkflowManagerToolboxLocation()
        arcpy.ImportToolbox(wmxDevUtilsToolbox, "WMXAdminUtils")

        # Save the existing workspaces to a file
        arcpy.ExportDataWorkspacesToExcel_WMXAdminUtils(excelWorksheetName)
        logPreviousToolMessages()

        # List the current workspaces
        result = arcpy.ListAllDataWorkspaces_WMXAdminUtils()
        logPreviousToolMessages()

        # Delete all of the workspaces from the DB
        allWorkspaces = result.getOutput(0)
        if len(allWorkspaces) > 0:
            allWorkspaces = allWorkspaces.split(";")
            
            for workspace in allWorkspaces:
                workspace = workspace.strip("'")
                workspace = workspace.strip("\"")
                arcpy.DeleteDataWorkspace_WMXAdminUtils(workspace)
                logPreviousToolMessages()

        # List the workspaces again
        result = arcpy.ListAllDataWorkspaces_WMXAdminUtils()
        logPreviousToolMessages()

        allWorkspaces = result.getOutput(0)
        if len(allWorkspaces) > 0:
            arcpy.AddError("Failed to delete all workspaces")

        # Recreate the workspaces from the spreadsheet that was just saved
        arcpy.CreateDataWorkspacesFromExcel_WMXAdminUtils(excelWorksheetName, "IGNORE_ALL_ERRORS")
        logPreviousToolMessages()

    except Exception, ex:
        printUsage()
        arcpy.AddError("Caught exception: " + str(ex))
コード例 #4
0
def main(args):
    """ If all checks passed this methode is called

    """
    try:
        _idf = IdentifyFeatures((args["e"], args["n"]), args["dist"])
        _parz_info = "[]"
        _count = 0
        while len(json.loads(_parz_info)) == 0:
            _parz_info = _idf.getparzinfo(float(args["dist"] + _count * 1.0))
            _count += 1
        arcpy.SetParameter(arcpy.GetArgumentCount() - 2, _parz_info)
        arcpy.AddMessage("{0} parcell(s) found".format(
            len(json.loads(_parz_info))))
        return True
    except Exception as _err:
        arcpy.AddError(_err)
        return False
コード例 #5
0
def main():

    try:
        # Get the input parameters to this tool
        if arcpy.GetArgumentCount() != 3:
            raise Exception("Incorrect number of arguments")

        dataWorkspaceName = arcpy.GetParameterAsText(0)
        dataWorkspaceSde = arcpy.GetParameterAsText(1)
        emailNotificationName = arcpy.GetParameterAsText(2)

        # Get any necessary licenses before importing the toolbox
        checkOutLicenses("", ["JTX"])

        # Import the Workflow Manager toolbox
        wmxToolbox = getWorkflowManagerToolboxLocation()
        arcpy.ImportToolbox(wmxToolbox, "WMXAdminUtils")
        arcpy.env.overwriteOutput = True

        # Create the spatial notification
        snName = "Monitor all FCs (Sample 1)"
        snDesc = "This spatial notification will monitor all of the feature classes in the specified workspace for any changes"
        summarize = "SUMMARIZE"
        arcpy.CreateSpatialNotificationWithEmailNotifier_WMXAdminUtils(
            snName, emailNotificationName, snDesc, summarize)
        logPreviousToolMessages()

        # Get the feature class list from the database
        arcpy.env.workspace = dataWorkspaceSde
        fcList = arcpy.ListFeatureClasses()

        # Add a dataset condition for each feature class
        changeCond = "ALWAYS"
        for fc in fcList:
            arcpy.AddDatasetConditionToSN_WMXAdminUtils(
                snName, dataWorkspaceName, fc, changeCond, "#", "#", "#", "#")
            logPreviousToolMessages()

    except Exception, ex:
        printUsage()
        arcpy.AddError("Caught exception: " + str(ex))
コード例 #6
0
#-------------------------------------------------------------------------------
# Name:        module1
# Purpose:
#
# Author:      calebma
#
# Created:     24/05/2016
# Copyright:   (c) calebma 2016
# Licence:     <your licence>
#-------------------------------------------------------------------------------
import arcpy
import sys
sys.path.append(r'\\arcserver1\GIS\MPWD\_Basemap\ESRI\Scripts\Toolbox')
from mpwd_lib import permits

if __name__ == '__main__':

    # get arguments
    args = [arcpy.GetParameter(i) for i in range(arcpy.GetArgumentCount() - 2)]

    # run it
    url, out_fs = permits.chicken_permits(*args)
    arcpy.AddMessage(url)
コード例 #7
0
# Map document file - usually passed via File Iterator, pass as parameter 0
file = arcpy.GetParameterAsText(0)
# Layers to hide - pass as string in parameter 1, delimit with pipe (|)
hideLayers = arcpy.GetParameterAsText(1).split("|")
# Layers to show - pass as string in parameter 2, delimit with pipe (|)
showLayers = arcpy.GetParameterAsText(2).split("|")
# Save the output in a different filename (same folder) - pass as string in parameter 3;
# if not set, will overwrite the original file
saveAs = re.sub(r'[\\/:"*?<>|]+', "", arcpy.GetParameterAsText(3))

# Add text replacement parameters
i = 3
replaceText = []
replaceTextWith = []

while x < arcpy.GetArgumentCount():
    replaceText.append(arcpy.GetParameterAsText(x))
    x += 1
    replaceTextWidth.append(arcpy.GetParameterAsText(x))
    x += 1

# Open map document
mxd = arcpy.mapping.MapDocument(file)

# Remove items in showLayers from hideLayers
for item in showLayers:
	while hideLayers.count(item) > 0:
		hideLayers.remove(item)

# Loop through all dataframes
for df in arcpy.mapping.ListDataFrames(mxd):
コード例 #8
0
print "Started at %s..." % starttime

# Ensure the Aeronautical extension is available. Exit if it is not.
availability = arcpy.CheckExtension("Aeronautical")
if availability != "Available":
    sys.exit('"Aeronautical" extension unavailable: %s' % availability)

try:
    arcpy.CheckOutExtension("Aeronautical")
    workspace = "FAA_Airports.gdb"
    runwayCenterlinesFC = 'RunwayCenterlinesForSurfacesWithZ_NewElevations'
    surfaceFC = 'ObstructionIdSurface'
    approachTypesTable = "ApproachTypeCode"

    # Use parameters from command line if provided.
    paramCount = arcpy.GetArgumentCount()
    if paramCount > 1:
        workspace = arcpy.GetParameterAsText(0)
    if paramCount > 2:
        runwayCenterlines = arcpy.GetParameterAsText(1)
    if paramCount > 3:
        surfaceFC = arcpy.GetParameterAsText(2)
    if paramCount > 4:
        approachTypesTable = arcpy.GetParameterAsText(3)
    del paramCount

    # Make sure the workspace exists.
    if not arcpy.Exists(workspace):
        # "Error in accessing the workspace"
        arcpy.AddIDMessage("ERROR", 198)
コード例 #9
0
def main():

    try:
        # Get the input parameters to this tool
        if arcpy.GetArgumentCount() != 0:
            raise Exception("Incorrect number of arguments")

        polygonFC = ".\\SampleData.gdb\\Quadrants"

        # Get any necessary licenses before importing the toolbox
        checkOutLicenses("", ["JTX"])

        # Import the Workflow Manager toolbox
        wmxToolbox = getWorkflowManagerToolboxLocation()
        arcpy.ImportToolbox(wmxToolbox, "WMXAdminUtils")
        arcpy.env.overwriteOutput = True

        # Make a feature layer from the polygon FC passed in;
        # features will be selected from this layer
        polygonLayer = "PolygonLayer"
        arcpy.MakeFeatureLayer_management(polygonFC, polygonLayer)

        # Iterate through all of the features in this feature class
        rows = arcpy.SearchCursor(polygonFC)
        counter = 1
        for row in rows:
            # The OBJECTID field will be unique for all features,
            # so retrieve its value for each feature and create a new
            # selection based on this value.
            objectID = row.OBJECTID
            arcpy.SelectLayerByAttribute_management(
                polygonLayer, "NEW_SELECTION", "OBJECTID = " + str(objectID))

            # Create a new spatial notifier
            snName = "Monitor Region " + str(counter) + " (Sample 3)"
            notifSubject = "A match was found in region " + str(counter)
            notifMessage = "----------\n"\
                           "Job: [SN:CHANGE_JOB_ID]\n"\
                           "Feature [SN:CHANGE_FEATURE_ID] was modified at [SN:CHANGE_TIME]"
            notifSubscribers = buildSubscriberString(objectID)
            snDesc = "This spatial notification will monitor all of the features in the region bounded by the polygon with OBJECTID " + str(
                objectID)
            summarize = "SUMMARIZE"
            arcpy.CreateSpatialNotificationWithEmailNotifier2_WMXAdminUtils(
                snName, notifSubject, notifMessage, notifSubscribers, "#", "#",
                snDesc, summarize)
            logPreviousToolMessages()

            # Add an area condition for this spatial notifier
            #
            # NOTE: To see the full list of options available for each argument,
            # launch the GP tool from ArcMap or ArcCatalog.  The arguments
            # correspond to options provided by Workflow Manager.
            geomOp = "INTERSECTS"
            doNotUseInverse = "USE_OPERATION"
            useFeature = "USE_SELECTED_FEATURE"
            arcpy.AddAreaEvaluatorToSN_WMXAdminUtils(snName, geomOp,
                                                     doNotUseInverse,
                                                     useFeature, polygonLayer)
            logPreviousToolMessages()

            # Increment the counter and move on to the next feature
            counter += 1

        # Free up any cursor objects and layers
        if row != None:
            del row
        if rows != None:
            del rows

        arcpy.Delete_management(polygonLayer)

    except Exception, ex:
        printUsage()
        arcpy.AddError("Caught exception: " + str(ex))
コード例 #10
0
__author__ = "spowell"
import arcpy

try:
    data_set = arcpy.GetParameterAsText(0)
    is_compress_db = False
    if arcpy.GetArgumentCount() > 1:
        is_compress_db = arcpy.GetParameterAsText(1)
    work_space = arcpy.env["scriptWorkspace"]
    assert work_space

    data_set_desc = arcpy.Describe(data_set)
    if not data_set_desc.isVersioned:
        arcpy.AddMessage(f"Disallowing new connections.")
        arcpy.AcceptConnections(work_space, False)
        arcpy.AddMessage(f"Disconnecting all Users.")
        arcpy.DisconnectUser(work_space, "ALL")
        arcpy.AddMessage(f"Registering {data_set} as Versioned.")
        arcpy.RegisterAsVersioned_management(data_set, "EDITS_TO_BASE")
        if is_compress_db:
            arcpy.AddMessage(
                f"Compressing geodatabase, this could take some time.")
            arcpy.Compress_management(work_space)
        arcpy.AddMessage(f"Accepting User Connections.")
        arcpy.AcceptConnections(work_space, True)
    else:
        arcpy.AddMessage(
            f"Nothing to version, {data_set} is already registered as versioned."
        )

except Exception as e:
コード例 #11
0
    except arcpy.ExecuteError:
        line, filename, synerror = trace()
        log.error("error on line: %s" % line)
        log.error("error in file name: %s" % __file__)
        log.error("with error message: %s" % synerror)
        log.error("ArcPy Error Message: %s" % arcpy.GetMessages(2))
    except FunctionError as f_e:
        messages = f_e.args[0]
        arcpy.AddError(messages)
        log.error("error in function: %s" % messages["function"])
        log.error("error on line: %s" % messages["line"])
        log.error("error in file name: %s" % __file__)
        log.error("with error message: %s" % messages["synerror"])
        log.error("ArcPy Error Message: %s" % messages["arc"])
    except:
        line, filename, synerror = trace()
        log.error("error on line: %s" % line)
        log.error("error in file name: %s" % __file__)
        log.error("with error message: %s" % synerror)
    finally:
        logging.shutdown()


#--------------------------------------------------------------------------
if __name__ == "__main__":
    env.overwriteOutput = True
    argv = tuple(
        arcpy.GetParameterAsText(i) for i in range(arcpy.GetArgumentCount()))
    main(*argv)
コード例 #12
0
import arcpy
# Get the spatial reference from the tool dialog.
txt_param = arcpy.GetParameterAsText(1)
spatial_ref = arcpy.GetParameter(0)
option_param = arcpy.GetParameterAsText(2)

# Display ArgumentCount
arcpy.AddMessage("ArgumentCount is: {0}".format(arcpy.GetArgumentCount()))
# Display txt_param
arcpy.AddMessage("txt_param is: {0}".format(txt_param))
# Display the Spatial Reference properties
arcpy.AddMessage("Name is: {0}".format(spatial_ref.name))
arcpy.AddMessage("Type is: {0}".format(spatial_ref.type))
arcpy.AddMessage("Factory code is: {0}".format(spatial_ref.factoryCode))
コード例 #13
0
# FUNCTIONS ========================================
def Geo2Arithmetic(inAngle):
    inAngle = math.fmod(inAngle, 360.0)
    #0 to 90
    if (inAngle >= 0.0 or inAngle <= 90.0):
        outAngle = math.fabs(inAngle - 90.0)

    # 90 to 360
    if (inAngle >= 90.0 or inAngle < 360.0):
        outAngle = 360.0 - (inAngle - 90.0)

    return float(outAngle)


# ARGUMENTS & LOCALS ===============================
argCount = arcpy.GetArgumentCount()

inFeature = arcpy.GetParameterAsText(0)
range = float(arcpy.GetParameterAsText(1))  #1000.0 # meters
bearing = float(arcpy.GetParameterAsText(2))  #45.0 # degrees
traversal = float(arcpy.GetParameterAsText(3))  #60.0 # degrees
outFeature = arcpy.GetParameterAsText(4)

webMercator = ""
if argCount >= 6:
    webMercator = arcpy.GetParameterAsText(5)

deleteme = []
debug = False
leftAngle = 0.0  # degrees
rightAngle = 90.0  # degrees
コード例 #14
0
def main():

    try:
        # Error checking and argument fetching
        if arcpy.GetArgumentCount() < 1:
            raise InvalidArgumentError("Required argument missing")

		# Set up the tool's parameters
        paramIndex = 0
        jobsTable = arcpy.GetParameterAsText(paramIndex)
        paramIndex += 1
        sqlQuery = arcpy.GetParameterAsText(paramIndex)
        paramIndex += 1
        wmxDbAlias = arcpy.GetParameterAsText(paramIndex)
        paramIndex += 1

        # Import the Workflow Manager toolbox
        wmxToolbox = getWorkflowManagerToolboxLocation()
        arcpy.ImportToolbox(wmxToolbox, "WMXAdminUtils")

        # Get the list of jobs matching the query
        result = arcpy.ListJobs_WMXAdminUtils(jobsTable, sqlQuery, wmxDbAlias)
        logPreviousToolMessages()
        numOutputs = result.outputCount

        if numOutputs <= 0:
            return
        
        # Output is a semicolon-delimited list of job IDs, so split up the
        # list, as required.
        jobListString = result.getOutput(0)
        if jobListString == None or len(jobListString) <= 0:
            arcpy.AddMessage("No jobs matched query")
            return

        jobsToDelete = jobListString.split(";")
        arcpy.AddMessage("Jobs to delete: " + str(jobListString))

        # Set up the progress bar
        arcpy.SetProgressor("step", "Deleting jobs...", 0, len(jobsToDelete), 1)

        # Delete each job
        jobCount = 0
        jobsDeleted = []
        for job in jobsToDelete:
            arcpy.SetProgressorLabel("Deleting job " + str(job))
            arcpy.DeleteJob_WMXAdminUtils(job, wmxDbAlias)
            logPreviousToolMessages()
            jobCount += 1
            jobsDeleted.append(job)
            
            arcpy.SetProgressorPosition(jobCount)

        # Set the return value for this tool (a multivalue containing the list of IDs
        # for the jobs that were deleted)
        jobsDeletedStr = ""
        for jobId in jobsDeleted:
            jobsDeletedStr += jobId + ";"

        jobsDeletedStr = jobsDeletedStr.rstrip(";")
        arcpy.SetParameterAsText(paramIndex, jobsDeletedStr)
        arcpy.AddMessage("Deleted jobs: " + jobsDeletedStr)

    except Exception, ex:
        arcpy.AddError("Caught exception: " + str(ex))
コード例 #15
0
                GPMsg()
                pass

        # return pivot point
        try:
            pivot_point = "{0} {1}".format(*pivot_point)
        except:
            pivot_point = None

        return pivot_point


if __name__ == '__main__':
    """ArcGIS script tool interface

    Arguments:

    Input_features
    Output_features
    Rotation_angle
    Rotation_point ("CENTER","LOWER_LEFT",...,"XY")
    Pivot point (ignored unless Rotation_point is "XY")
    Pivot point value (derived)
    """
    # last argument is derived
    numArgs = arcpy.GetArgumentCount() - 1
    argv = tuple([arcpy.GetParameterAsText(i) for i in range(numArgs)])
    xy = RotateFeatureClass(*argv)
    # populate derived parameter (pivot point)
    arcpy.SetParameterAsText(5, xy)
コード例 #16
0
import arcpy

nparms = arcpy.GetArgumentCount()

arcpy.AddMessage("You have specifed " + str(nparms) + " parameters")
arcpy.AddMessage(arcpy.GetParameterAsText(0))

#inputs
inputFeats = arcpy.GetParameterAsText(0)
bufd = arcpy.GetParameterAsText(1)

#outputs
outFeats = arcpy.GetParameterAsText(2)  #r"C:\temp\growthM\tempOut.shp"

#Code to do our Process Here:
arcpy.Buffer_analysis(inputFeats, outFeats, bufd)
#arcpy.SetParameterAsText(2, outFeats)

arcpy.AddMessage("Completed")
コード例 #17
0
    """ Entrypoint for the application.

    - logs some basic infos
    initialises the parameters and checks the input parameter sys.argv

    Args:

    Returns:
        exitcode  0: no error
        exitcode -1: could not init parameter
        exitcode -2. could not get ParzInfo

    Raises:
    """
    _version = 0.5
    arcpy.SetParameter(arcpy.GetArgumentCount() - 1, _version)
    _exitcode, _args = init(sys.argv)
    if _exitcode == 0:
        try:
            if main(_args):
                arcpy.AddMessage("Parzinfo executed successfully")
            else:
                arcpy.AddError("could not get ParzInfo")
                _exitcode = -2
        except Exception as _err:
            arcpy.AddError(_err)

    else:
        arcpy.AddError("could not init parameter")
        _exitcode = -1
コード例 #18
0
    try:
        arcpy.AddMessage("Creating Database Connection File...")
        # Process: Create Database Connection File...
        # Usage:  out_file_location, out_file_name, DBMS_TYPE, instnace, account_authentication, username, password, database, save_username_password(must be true)
        arcpy.CreateDatabaseConnection_management(out_folder_path=out_folder_path, out_name=Connection_File_Name, database_platform=database_type, instance=instance, database=database, account_authentication=account_authentication, username=dbuser_name, password=dbuser_pwd, save_user_pass="******")
        for i in range(arcpy.GetMessageCount()):
            if "000565" in arcpy.GetMessage(i):   #Check if database connection was successful
                arcpy.AddReturnMessage(i)
                arcpy.AddMessage("++++++++++++++++++")
                arcpy.AddMessage("Exiting!!")
                arcpy.AddMessage("++++++++++++++++++")
                sys.exit(3)
            else:
                arcpy.AddReturnMessage(i)
        arcpy.AddMessage("++++++++++++++++++")
    except:
        for i in range(arcpy.GetMessageCount()):
            arcpy.AddReturnMessage(i)
'''-------------------------------------------------------------------------------
# START script
-------------------------------------------------------------------------------'''
# This test allows the script to be used from the operating
# system command prompt (stand-alone), in a Python IDE,
# as a geoprocessing script tool, or as a module imported in
# another script
if __name__ == '__main__':
    # Arguments are optional
    argv = tuple(arcpy.GetParameterAsText(i)
        for i in range(arcpy.GetArgumentCount()))
    main(*argv)
コード例 #19
0
def main():

    try:
        # Get the input parameters to this tool
        if arcpy.GetArgumentCount() != 3:
            raise Exception("Incorrect number of arguments")

        adUsersGroup = arcpy.GetParameterAsText(0)
        adGroupsGroup = arcpy.GetParameterAsText(1)
        wmxAdminGroup = arcpy.GetParameterAsText(2)

        # Get any necessary licenses before importing the toolbox
        checkOutLicenses("", ["JTX"])

        # Import the Workflow Manager toolbox
        wmxToolbox = getWorkflowManagerToolboxLocation()
        arcpy.ImportToolbox(wmxToolbox, "WMXAdminUtils")

        # Run the active directory import
        preserve = "NO_PRESERVE"
        arcpy.ImportActiveDirectoryConfiguration_WMXAdminUtils(
            adUsersGroup, adGroupsGroup, preserve)
        logPreviousToolMessages()

        # Ensure that all of the group permissions are in a known state
        #
        # The sequence of events shown here is arbitrary; a real-life example would
        # likely be set up differently

        # Grant everything to everyone
        arcpy.ModifyPrivilegeAssignment_WMXAdminUtils("[All]", "[All]",
                                                      "GRANT")
        logPreviousToolMessages()

        # Remove some particular permissions from the groups
        arcpy.ModifyPrivilegeAssignment_WMXAdminUtils("DeleteJobs", "[All]",
                                                      "REVOKE")
        logPreviousToolMessages()
        arcpy.ModifyPrivilegeAssignment_WMXAdminUtils("DeleteVersion", "[All]",
                                                      "REVOKE")
        logPreviousToolMessages()

        # Add the permissions back to the administrators group
        arcpy.ModifyPrivilegeAssignment_WMXAdminUtils("[All]", wmxAdminGroup,
                                                      "GRANT")
        logPreviousToolMessages()

        # Now, make sure that all of the users in the admin group have administrator
        # access to the WMX DB
        result = arcpy.ListUsers_WMXAdminUtils(wmxAdminGroup)
        logPreviousToolMessages()

        userListString = result.getOutput(0)
        if userListString != None and len(userListString) > 0:
            users = userListString.split(";")

            arcpy.ModifyAdministratorAccess_WMXAdminUtils(
                "[All]", "REVOKE", "PRESERVE")
            logPreviousToolMessages()

            for user in users:
                arcpy.ModifyAdministratorAccess_WMXAdminUtils(
                    user, "GRANT", "PRESERVE")
                logPreviousToolMessages()

    except Exception, ex:
        printUsage()
        arcpy.AddError("Caught exception: " + str(ex))