PembrokePSwman.psm1

Write-Verbose 'Importing from [C:\projects\pembrokepstman\PembrokePSwman\private]'
# .\PembrokePSwman\private\Get-SubTaskData.ps1
function Get-SubTaskData {
    <#
    .DESCRIPTION
        This function will gather Tasks based on a requested Status
    .PARAMETER Task_Type_Id
        A Status is required.
    .PARAMETER RestServer
        A RestServer is Required.
    .EXAMPLE
        Get-SubTaskData -Task_Type_Id 1 -RestServer localhost
    .NOTES
        This will return a hashtable of data from the PPS database.
    #>

    [CmdletBinding()]
    [OutputType([hashtable])]
    param(
        [Parameter(Mandatory=$true)][String]$Task_Type_Id,
        [Parameter(Mandatory=$true)][String]$RestServer
    )
    if (Test-Connection -Count 1 $RestServer -Quiet) {
        try
        {
            Write-LogLevel -Message "Gathering SubTask data for Task_Type_Id: $Task_Type_Id." -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel DEBUG           
            $URL = "http://$RestServer/PembrokePS/public/api/api.php/subtask_generator?filter=task_type_id,eq," + $Task_Type_Id + "&transform=1"
            Write-LogLevel -Message "$URL" -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel TRACE
            $SubTaskData = Invoke-RestMethod -Method Get -Uri "$URL" -UseBasicParsing
        }
        catch
        {
            $ErrorMessage = $_.Exception.Message
            $FailedItem = $_.Exception.ItemName        
            Throw "Get-SubTaskData: $ErrorMessage $FailedItem"
        }
        $SubTaskData
    } else {
        Throw "Get-SubTaskData: Unable to reach Rest server: $RestServer."
    }
    
}
# .\PembrokePSwman\private\Get-WmanModuleSet.ps1
function Get-WmanModuleSet {
    <#
    .DESCRIPTION
        This function will gather Modules based on a WorkflowManager ID.
    .PARAMETER WmanId
        A Status is required.
    .PARAMETER RestServer
        A RestServer is Required.
    .EXAMPLE
        Get-WmanModuleSet -WmanId 1 -RestServer localhost
    .NOTES
        This will return a hashtable of data from the PPS database.
    #>

    [CmdletBinding()]
    [OutputType([hashtable])]
    param(
        [Parameter(Mandatory=$true)][String]$WmanId,
        [Parameter(Mandatory=$true)][String]$RestServer
    )
    if (Test-Connection -Count 1 $RestServer -Quiet) {
        try
        {
            Write-LogLevel -Message "Gathering Modules for Workflow Manager: $WmanId." -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel DEBUG
            $URL = "http://$RestServer/PembrokePS/public/api/api.php/workflow_manager_modules?include=additional_ps_modules&filter[]=result_id,eq,1&filter[]=workflow_manager_id,eq," + $WmanId +"&transform=1"
            Write-LogLevel -Message "$URL" -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel TRACE
            $WmanModules = Invoke-RestMethod -Method Get -Uri "$URL" -UseBasicParsing
        }
        catch
        {
            $ErrorMessage = $_.Exception.Message
            $FailedItem = $_.Exception.ItemName        
            Throw "Get-WmanModuleSet: $ErrorMessage $FailedItem"
        }
        $WmanModules
    } else {
        Throw "Get-WmanModuleSet: Unable to reach Rest server: $RestServer."
    }
    
}
# .\PembrokePSwman\private\Get-WmanStatus.ps1
function Get-WmanStatus {
    <#
    .DESCRIPTION
        This function will gather Status information from PembrokePS web/rest for a Workflow_Manager
    .PARAMETER ComponentId
        An ID is required.
    .PARAMETER RestServer
        A Rest Server is required.
    .EXAMPLE
        Get-WmanStatus -ComponentId 1 -RestServer localhost
    .NOTES
        This will return a hashtable of data from the PPS database.
    #>

    [CmdletBinding()]
    [OutputType([hashtable])]
    param(
        [Parameter(Mandatory=$true)][int]$ComponentId,
        [Parameter(Mandatory=$true)][string]$RestServer
    )
    if (Test-Connection -Count 1 $RestServer -Quiet) {
        try
        {
            Write-LogLevel -Message "Gathering Component: $ComponentId Status." -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel TRACE
            $ComponentStatusData = (Get-ComponentStatus -ComponentType Workflow_Manager -ComponentId $ComponentId -RestServer $RestServer).workflow_manager
        }
        catch
        {
            $ErrorMessage = $_.Exception.Message
            $FailedItem = $_.Exception.ItemName        
            Throw "Get-WmanStatus: $ErrorMessage $FailedItem"
        }
        $ComponentStatusData
    } else {
        Throw "Get-WmanStatus: Unable to reach Rest server: $RestServer."
    }
    
}
# .\PembrokePSwman\private\Get-WmanTableName.ps1
function Get-WmanTableName {
    <#
    .DESCRIPTION
        This function will gather The tableName for the Workflow Manager type.
    .PARAMETER RestServer
        A Rest Server is required.
    .PARAMETER Type_ID
        A Workflow Manager Type_ID is required.
    .EXAMPLE
        Get-WmanTableName -RestServer localhost -Type_ID 1
    .NOTES
        This will return a hashtable of data from the PPS database.
    #>

    [CmdletBinding()]
    [OutputType([hashtable])]
    param(
        [Parameter(Mandatory=$true)][string]$RestServer,
        [Parameter(Mandatory=$true)][int]$Type_ID
    )
    if (Test-Connection -Count 1 $RestServer -Quiet) {
        try
        {
            Write-LogLevel -Message "Gathering TableName for Wman Type: $Type_ID." -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel DEBUG
            $URL = "http://$RestServer/PembrokePS/public/api/api.php/workflow_manager_type/$Type_ID"
            Write-LogLevel -Message "$URL" -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel TRACE
            $TableNameData = Invoke-RestMethod -Method Get -Uri "$URL" -UseBasicParsing
        }
        catch
        {
            $ErrorMessage = $_.Exception.Message
            $FailedItem = $_.Exception.ItemName        
            Throw "Get-WmanTableName: $ErrorMessage $FailedItem"
        }
        $TableNameData
    } else {
        Throw "Get-WmanTableName: Unable to reach Rest server: $RestServer."
    }
    
}
# .\PembrokePSwman\private\Get-WmanTaskSet.ps1
function Get-WmanTaskSet {
    <#
    .DESCRIPTION
        This function will gather task information for a Wman in a with a specific task status.
    .PARAMETER RestServer
        A Rest Server is required.
    .PARAMETER TableName
        A TableName is optional, tasks is default.
    .PARAMETER Status_ID
        A Status_ID is required.
    .PARAMETER WmanId
        A WmanId is required.
    .EXAMPLE
        Get-WmanTaskSet -RestServer -localhost -Status_ID 7 -TableName tasks
    .NOTES
        This will return a hashtable of data from the PPS database.
    #>

    [CmdletBinding()]
    [OutputType([hashtable])]
    param(
        [Parameter(Mandatory=$true)][String]$RestServer,
        [string]$TableName="Tasks",
        [Parameter(Mandatory=$true)][Int]$Status_ID,
        [Parameter(Mandatory=$true)][Int]$WmanId
    )
    if (Test-Connection -Count 1 $RestServer -Quiet) {
        try
        {
            Write-LogLevel -Message "Gathering Wman Tasks with Status: $Status_ID, from table: $TableName." -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel DEBUG
            $URL = "http://$RestServer/PembrokePS/public/api/api.php/" + $TableName + "?filter[]=status_id,eq," + $Status_ID + '&filter[]=workflow_manager_id,eq,' + $WmanId + '&transform=1'
            Write-LogLevel -Message "Url is: $URL" -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel TRACE
            $TaskData = Invoke-RestMethod -Method Get -Uri "$URL" -UseBasicParsing
        }
        catch
        {
            $ErrorMessage = $_.Exception.Message
            $FailedItem = $_.Exception.ItemName        
            Throw "Get-WmanTaskSet: $ErrorMessage $FailedItem"
        }
        $TaskData
    } else {
        Throw "Get-WmanTaskSet: Unable to reach Rest server: $RestServer."
    }
    
}
# .\PembrokePSwman\private\Invoke-CancelRunningTaskSet.ps1
function Invoke-CancelRunningTaskSet {
    <#
    .DESCRIPTION
        This function will Set any Running task to Cancelled.
    .PARAMETER RestServer
        A Rest Server is required.
    .PARAMETER TableName
        A TableName is optional, default is tasks.
    .PARAMETER ID
        An ID is Required.
    .EXAMPLE
        Invoke-CancelRunningTaskSet -RestServer localhost -TableName tasks
    .NOTES
        This will return a hashtable of data from the PPS database.
    #>

    [CmdletBinding()]
    [OutputType([Int])]
    [OutputType([Boolean])]
    param(
        [Parameter(Mandatory=$true)][string]$RestServer,
        [Parameter(Mandatory=$true)][int]$ID,
        [string]$TableName="tasks"
    )
    if (Test-Connection -Count 1 $RestServer -Quiet) {
        try
        {
            # Get a list of Running tasks
            $TableName = $TableName.ToLower()
            Write-LogLevel -Message "Gathering Running Tasks for Wman: $ID from table: $TableName" -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel DEBUG
            $RunningTasks = (Get-WmanTaskSet -RestServer $RestServer -TableName $TableName -STATUS_ID 8 -WmanId $ID).$TableName
            $RunningTasksCount = ($RunningTasks | Measure-Object).count
            Write-LogLevel -Message "Cancelling: $RunningTasksCount tasks from table: $TableName" -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel DEBUG
            if($RunningTasksCount -gt 0) {
                foreach($Task in $RunningTasks){
                    # Foreach task, set it to Complete/Aborted.
                    $TaskId = $Task.ID
                    $body = @{STATUS_ID = "10"
                                RESULT_ID = "6"
                            }
                    Write-LogLevel -Message "Cancelling Running task: $TaskId from table: $TableName" -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel DEBUG
                    $RestReturn = Invoke-UpdateTaskTable -RestServer $RestServer -TableName $TableName -TaskID $TaskId -Body $body
                }
            } else {
                # No tasks to Cancel
                Write-LogLevel -Message "No Tasks to Cancel for Wman: $ID" -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel INFO
            }
        }
        catch
        {
            $ErrorMessage = $_.Exception.Message
            $FailedItem = $_.Exception.ItemName        
            Throw "Invoke-CancelRunningTaskSet: $ErrorMessage $FailedItem"
        }
        $RestReturn
    } else {
        Throw "Invoke-CancelRunningTaskSet: Unable to reach Rest server: $RestServer."
    }
    
}
# .\PembrokePSwman\private\Invoke-CancelStagedTaskSet.ps1
function Invoke-CancelStagedTaskSet {
    <#
    .DESCRIPTION
        This function will Set any Staged task to Cancelled.
    .PARAMETER RestServer
        A Rest Server is required.
    .PARAMETER TableName
        A TableName is optional, default is tasks.
    .PARAMETER ID
        An ID is Required.
    .EXAMPLE
        Invoke-CancelStagedTaskSet -RestServer localhost -TableName tasks
    .NOTES
        This will return a hashtable of data from the PPS database.
    #>

    [CmdletBinding()]
    [OutputType([Int])]
    [OutputType([Boolean])]
    param(
        [Parameter(Mandatory=$true)][string]$RestServer,
        [Parameter(Mandatory=$true)][int]$ID,
        [string]$TableName="tasks"
    )
    if (Test-Connection -Count 1 $RestServer -Quiet) {
        try
        {
            # Get a list of Staged tasks
            $TableName = $TableName.ToLower()
            Write-LogLevel -Message "Gathering Staged Tasks for Wman: $ID from table: $TableName" -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel DEBUG
            $StagedTasks = (Get-WmanTaskSet -RestServer $RestServer -TableName $TableName -STATUS_ID 14 -WmanId $ID).$TableName
            $StagedTasksCount = ($StagedTasks | Measure-Object).count
            Write-LogLevel -Message "Cancelling: $StagedTasksCount tasks from table: $TableName" -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel DEBUG
            if($StagedTasksCount -gt 0) {
                foreach($Task in $StagedTasks){
                    # Foreach task, set it to Complete/Aborted.
                    $TaskId = $Task.ID
                    $body = @{STATUS_ID = "10"
                                RESULT_ID = "6"
                            }
                    Write-LogLevel -Message "Cancelling Staged task: $TaskId from table: $TableName" -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel DEBUG
                    $RestReturn = Invoke-UpdateTaskTable -RestServer $RestServer -TableName $TableName -TaskID $TaskId -Body $body
                }
            } else {
                # No tasks to Cancel
                Write-LogLevel -Message "No Tasks to Cancel for Wman: $ID" -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel INFO
            }
        }
        catch
        {
            $ErrorMessage = $_.Exception.Message
            $FailedItem = $_.Exception.ItemName        
            Throw "Invoke-CancelStagedTaskSet: $ErrorMessage $FailedItem"
        }
        $RestReturn
    } else {
        Throw "Invoke-CancelStagedTaskSet: Unable to reach Rest server: $RestServer."
    }
    
}
# .\PembrokePSwman\private\Invoke-ExecutionPath.ps1
function Invoke-ExecutionPath {
    <#
    .DESCRIPTION
        This function will gather Status information from PembrokePS web/rest for a Queue_Manager
    .PARAMETER ExecutionPath
        A ExecutionPath is required.
    .EXAMPLE
        Invoke-ExecutionPath -ExecutionPath C:\PembrokePS\wman\scripts\somefile.ps1
    .NOTES
        This will return a hashtable of data from the PPS database.
    #>

    [CmdletBinding()]
    [OutputType([boolean])]
    param(
        [Parameter(Mandatory=$true)][string]$ExecutionPath
    )
    try
    {
        # Validate the Path Exists and Perform the task.
        if(Test-Path -Path $ExecutionPath){
            Write-LogLevel -Message "Executing Script: $ExecutionPath, with Args: $Task_Args" -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel DEBUG
            . "$ExecutionPath" $Task_Args
        } else {
            $script:TaskResult = 4
            Write-LogLevel -Message "File: $ExecutionPath does not exist." -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel ERROR  
        }
        return $script:TaskResult
    }
    catch
    {
        $ErrorMessage = $_.Exception.Message
        $FailedItem = $_.Exception.ItemName        
        Throw "Invoke-ExecutionPath: $ErrorMessage $FailedItem"
    }

}
# .\PembrokePSwman\private\Invoke-GenerateSubTask.ps1
function Invoke-GenerateSubTask {
    <#
    .DESCRIPTION
        This function will Create a subtask.
    .PARAMETER RestServer
        A Rest Server is required.
    .PARAMETER TableName
        An TableName is required.
    .PARAMETER TaskID
        An TaskID is required.
    .PARAMETER Body
        A Column/Field is required.
    .EXAMPLE
        Invoke-GenerateSubTask -RestServer localhost -SubTaskTypeId 2 -TableName tasks -Target_ID 1
    .NOTES
        This will return a hashtable of data from the PPS database.
    #>

    [CmdletBinding()]
    [OutputType([hashtable])]
    param(
        [Parameter(Mandatory=$true)][string]$TableName,
        [Parameter(Mandatory=$true)][string]$RestServer,
        [Parameter(Mandatory=$true)][int]$SubTaskTypeId,
        [Parameter(Mandatory=$true)][int]$Target_ID
    )
    if (Test-Connection -Count 1 $RestServer -Quiet) {
        try
        {
            $body = @{STATUS_ID = "5"
                        RESULT_ID = "6"
                        LOG_FILE = "nolog"
                        WORKFLOW_MANAGER_ID = "9999"
                        TASK_TYPE_ID = "$SubTaskTypeId"
                        TARGET_ID = "$Target_ID"
                        ARGUMENTS = "NoArgs"
                        HIDDEN = "0"
            }
            Write-LogLevel -Message "Updating Task Table: $TableNAme, Task: $TaskId." -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel DEBUG
            $URL = "http://$RestServer/PembrokePS/public/api/api.php/$TableName"
            Write-LogLevel -Message "$URL" -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel TRACE
            $RestReturn = Invoke-RestMethod -Method Post -Uri "$URL" -body $body
            $ReturnData = @{NewTaskId = $RestReturn}
        }
        catch
        {
            $ErrorMessage = $_.Exception.Message
            $FailedItem = $_.Exception.ItemName        
            Throw "Invoke-GenerateSubTask: $ErrorMessage $FailedItem"
        }
        $ReturnData
    } else {
        Throw "Invoke-GenerateSubTask: Unable to reach Rest server: $RestServer."
    }
    
}
# .\PembrokePSwman\private\Invoke-ImportWmanModuleSet.ps1
function Invoke-ImportWmanModuleSet {
    <#
    .DESCRIPTION
        This function will import additional Modules for a Workflow_Manager.
    .PARAMETER RestServer
        A RestServer is Required.
    .PARAMETER WmanId
        An WmanId is Required.
    .EXAMPLE
        Invoke-ImportWmanModuleSet -RestServer localhost -WmanId 1
    .NOTES
        This will import additional Modules for a Workflow_Manager.
    #>

    [CmdletBinding()]
    [OutputType([Boolean])]
    param(
        [Parameter(Mandatory=$true)][string]$RestServer,
        [Parameter(Mandatory=$true)][int]$WmanId
    )
    if (Test-Connection -Count 1 $RestServer -Quiet) {
        try
        {
            Write-LogLevel -Message "Getting additional Required Modules for Workflow Manager: $WmanId." -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel DEBUG
            $WmanModuleSet = ((Get-WmanModuleSet -WmanId $WmanId -RestServer $RestServer).workflow_manager_modules).additional_ps_modules | Where-Object {$_.STATUS_ID -eq 11}
            $WmanModuleSetCount = ($WmanModuleSet | Measure-Object).count
            if($WmanModuleSetCount -ge 1){
                foreach ($WmanModule in $WmanModuleSet) {
                    $ModuleName = $WmanModule.NAME
                    $GalleryName = $WmanModule.GALLERY_NAME
                    $Version = $WmanModule.MODULE_VERSION
                    Write-LogLevel -Message "Importing Module $ModuleName, version: $Version." -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel DEBUG
                    if($Version -eq "Latest"){
                        Import-Module -Name $GalleryName -Force
                    } else {
                        Import-Module $GalleryName -RequiredVersion $Version -Force
                    }
                    Invoke-Wait -Seconds 2
                }
            } else {
                Write-LogLevel -Message "No Modules to Import." -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel DEBUG
            }
        }
        catch
        {
            $ErrorMessage = $_.Exception.Message
            $FailedItem = $_.Exception.ItemName        
            Throw "Invoke-ImportWmanModuleSet: $ErrorMessage $FailedItem"
        }
    } else {
        Throw "Invoke-ImportWmanModuleSet: Unable to reach Rest server: $RestServer."
    }

}
    
# .\PembrokePSwman\private\Invoke-InstallWmanModuleSet.ps1
function Invoke-InstallWmanModuleSet {
    <#
    .DESCRIPTION
        This function will Install additional Modules for a Workflow_Manager.
    .PARAMETER RestServer
        A RestServer is Required.
    .PARAMETER WmanId
        An WmanId is Required.
    .EXAMPLE
        Invoke-InstallWmanModuleSet -RestServer localhost -WmanId 1
    .NOTES
        This will Install additional Modules for a Workflow_Manager.
    #>

    [CmdletBinding()]
    [OutputType([Boolean])]
    param(
        [Parameter(Mandatory=$true)][string]$RestServer,
        [Parameter(Mandatory=$true)][int]$WmanId
    )
    if (Test-Connection -Count 1 $RestServer -Quiet) {
        try
        {
            Write-LogLevel -Message "Getting additional Required Modules for Workflow Manager: $WmanId." -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel DEBUG
            $WmanModuleSet = ((Get-WmanModuleSet -WmanId $WmanId -RestServer $RestServer).workflow_manager_modules).additional_ps_modules | Where-Object {$_.STATUS_ID -eq 11}
            $WmanModuleSetCount = ($WmanModuleSet | Measure-Object).count
            if($WmanModuleSetCount -ge 1){
                foreach ($WmanModule in $WmanModuleSet) {
                    $ModuleName = $WmanModule.NAME
                    $GalleryName = $WmanModule.GALLERY_NAME
                    $Version = $WmanModule.MODULE_VERSION
                    Write-LogLevel -Message "Installing Module $ModuleName." -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel DEBUG
                    if($Version -eq "Latest"){
                        Install-Module -Name $GalleryName -Force
                    } else {
                        Install-Module -Name $GalleryName -RequiredVersion $Version -Force
                    }
                    Invoke-Wait -Seconds 2
                }
            } else {
                Write-LogLevel -Message "No Modules to Install." -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel DEBUG
            }
        }
        catch
        {
            $ErrorMessage = $_.Exception.Message
            $FailedItem = $_.Exception.ItemName        
            Throw "Invoke-InstallWmanModuleSet: $ErrorMessage $FailedItem"
        }
        $ReturnMessage
    } else {
        Throw "Invoke-InstallWmanModuleSet: Unable to reach Rest server: $RestServer."
    }

}
    
# .\PembrokePSwman\private\Invoke-QueueAssignedTaskSet.ps1
function Invoke-QueueAssignedTaskSet {
    <#
    .DESCRIPTION
        This function will Queue any assigned tasks to the current Workflow_Manager.
    .PARAMETER RestServer
        A Rest Server is required.
    .PARAMETER TableName
        A TableName is optional, default is tasks.
    .PARAMETER ID
        An ID is Required.
    .EXAMPLE
        Invoke-QueueAssignedTaskSet -RestServer localhost -TableName tasks
    .NOTES
        This will return a hashtable of data from the PPS database.
    #>

    [CmdletBinding()]
    [OutputType([Int])]
    [OutputType([Boolean])]
    param(
        [Parameter(Mandatory=$true)][string]$RestServer,
        [Parameter(Mandatory=$true)][int]$ID,
        [string]$TableName="tasks"
    )
    if (Test-Connection -Count 1 $RestServer -Quiet) {
        try
        {
            # Get a list of Assigned tasks
            $TableName = $TableName.ToLower()
            Write-LogLevel -Message "Queueing Assigned tasks for WMan: $ID" -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel DEBUG
            $AssignedTasks = (Get-WmanTaskSet -RestServer $RestServer -TableName $TableName -STATUS_ID 7 -WmanId $ID).$TableName
            $AssignedTasksCount = ($AssignedTasks | Measure-Object).count
            Write-LogLevel -Message "Queueing $AssignedTasksCount Assigned tasks for WMan: $ID" -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel DEBUG
            if($AssignedTasksCount -gt 0) {
                foreach($Task in $AssignedTasks){
                    # Foreach task, set it to Complete/Aborted.
                    $TaskId = $Task.ID
                    $body = @{STATUS_ID = "6"
                                RESULT_ID = "6"
                            }
                    Write-LogLevel -Message "Queueing task: $Task_Id, from table: $TableName." -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel DEBUG
                    $RestReturn = Invoke-UpdateTaskTable -RestServer $RestServer -TableName $TableName -TaskID $TaskId -Body $body
                }
            } else {
                # No tasks to queue
                Write-LogLevel -Message "No Tasks to Queue for Wman: $ID." -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel INFO
            }
        }
        catch
        {
            $ErrorMessage = $_.Exception.Message
            $FailedItem = $_.Exception.ItemName        
            Throw "Invoke-QueueAssignedTaskSet: $ErrorMessage $FailedItem"
        }
        $RestReturn
    } else {
        Throw "Invoke-QueueAssignedTaskSet: Unable to reach Rest server: $RestServer."
    }
    
}
# .\PembrokePSwman\private\Invoke-ReviewAssignedTaskSet.ps1
function Invoke-ReviewAssignedTaskSet {
    <#
    .DESCRIPTION
        This function will Start an Assigned task if the Workflow Manager is under its max Concurrent tasks.
    .PARAMETER RestServer
        A Rest Server is required.
    .PARAMETER TableName
        A TableName is optional, default is tasks.
    .PARAMETER MAX_CONCURRENT_TASKS
        A MAX_CONCURRENT_TASKS is required.
    .PARAMETER ID
        An ID is Required.
    .EXAMPLE
        Invoke-ReviewAssignedTaskSet -RestServer localhost -TableName tasks -MAX_CONCURRENT_TASKS 4
    .NOTES
        This will return a hashtable of data from the PPS database.
    #>

    [CmdletBinding()]
    [OutputType([Int])]
    [OutputType([Boolean])]
    param(
        [Parameter(Mandatory=$true)][string]$RestServer,
        [Parameter(Mandatory=$true)][Int]$MAX_CONCURRENT_TASKS,
        [Parameter(Mandatory=$true)][int]$ID,
        [string]$TableName="tasks"
    )
    if (Test-Connection -Count 1 $RestServer -Quiet) {
        try
        {
            # Get a list of Running tasks
            $TableName = $TableName.ToLower()
            Write-LogLevel -Message "Reviewing Assigned tasks for Wman: $ID for table: $TableName" -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel DEBUG
            $AssignedTasks = (Get-WmanTaskSet -RestServer $RestServer -TableName $TableName -STATUS_ID 7 -WmanId $ID).$TableName
            $AssignedTasksCount = ($AssignedTasks | Measure-Object).count
            Write-LogLevel -Message "Reviewing $AssignedTasksCount Assigned tasks for Wman: $ID for table: $TableName" -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel DEBUG
            if($AssignedTasksCount -gt 0) {
                # Determine the number of Running Tasks.
                Write-LogLevel -Message "Determining if the Current Running tasks for Wman: $ID is over its Max: $MAX_CONCURRENT_TASKS." -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel DEBUG
                $RunningTasks = (Get-WmanTaskSet -RestServer $RestServer -TableName $TableName -STATUS_ID 8 -WmanId $ID).$TableName
                $RunningTasksCount = ($RunningTasks | Measure-Object).count
                if(($RunningTasksCount -lt $MAX_CONCURRENT_TASKS) -and ($AssignedTasksCount -gt 0)) {
                    $Task = $AssignedTasks[0]
                    # Grab the First task in the list, and set it to staged.
                    $TaskId = $Task.ID
                    $body = @{STATUS_ID = "14"
                                RESULT_ID = "6"
                            }
                    Write-LogLevel -Message "Setting Task: $TaskId to Staged" -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel INFO
                    Invoke-UpdateTaskTable -RestServer $RestServer -TableName $TableName -TaskID $TaskId -Body $body
                    # Start the Workflow Wrapper.
                    Write-LogLevel -Message "Starting Task: $TaskId." -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel INFO
                    Start-AssignedTask -RestServer $RestServer -TaskId $TaskId -TableName $TableName
                    Invoke-Wait -Seconds 3
                    
                } else {
                    # Wman is at its Max.
                    Write-LogLevel -Message "Wman: $ID is at its max: $MAX_CONCURRENT_TASKS tasks." -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel DEBUG
                }
            } else {
                # No Tasks to Start
                Write-LogLevel -Message "No Tasks to start at this time." -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel DEBUG
            }
        }
        catch
        {
            $ErrorMessage = $_.Exception.Message
            $FailedItem = $_.Exception.ItemName        
            Throw "Invoke-ReviewAssignedTaskSet: $ErrorMessage $FailedItem"
        }
    } else {
        Throw "Invoke-ReviewAssignedTaskSet: Unable to reach Rest server: $RestServer."
    }
    
}
# .\PembrokePSwman\private\Invoke-UpdateWmanData.ps1
function Invoke-UpdateWmanData {
    <#
    .DESCRIPTION
        This function will update a column and field for a Workflow_Manager
    .PARAMETER ComponentId
        An ID is required.
    .PARAMETER RestServer
        A Rest Server is required.
    .PARAMETER Column
        A Column/Field is required.
    .PARAMETER Value
        A Value is required.
    .EXAMPLE
        Invoke-UpdateWmanData -ComponentId 1 -RestServer localhost -Column STATUS_ID -Value 2
    .NOTES
        This will return a hashtable of data from the PPS database.
    #>

    [CmdletBinding()]
    [OutputType([hashtable])]
    param(
        [Parameter(Mandatory=$true)][int]$ComponentId,
        [Parameter(Mandatory=$true)][string]$RestServer,
        [Parameter(Mandatory=$true)][string]$Column,
        [Parameter(Mandatory=$true)][string]$Value
    )
    if (Test-Connection -Count 1 $RestServer -Quiet) {
        try
        {
            Write-LogLevel -Message "Updating Wman: $ComponentId, Column: $Column, Value: $Value" -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel DEBUG
            if ((Invoke-UpdateComponent -ComponentId $ComponentId -RestServer $RestServer -Column $Column -Value $Value -ComponentType workflow_manager) -eq 1) {
                # Good To go
            } else {
                Write-LogLevel -Message "Unable to update Wman: $ComponentId, Column: $Column, Value: $Value" -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel DEBUG
                Throw "Invoke-UpdateWmanData: Unable to update Wman data."
            }
        }
        catch
        {
            $ErrorMessage = $_.Exception.Message
            $FailedItem = $_.Exception.ItemName        
            Throw "Invoke-UpdateWmanData: $ErrorMessage $FailedItem"
        }
    } else {
        Throw "Invoke-UpdateWmanData: Unable to reach Rest server: $RestServer."
    }
    
}
# .\PembrokePSwman\private\Invoke-WmanShutdownTaskSet.ps1
function Invoke-WmanShutdownTaskSet {
    <#
    .DESCRIPTION
        This function will perform shutdown tasks for a Workflow_Manager
    .PARAMETER RestServer
        A RestServer is Required.
    .PARAMETER TableName
        A properties path is Required.
    .PARAMETER ID
        An ID is Required.
    .EXAMPLE
        Invoke-WmanShutdownTaskSet -RestServer localhost -TableName tasks -ID 1
    .NOTES
        This will return a hashtable of data from the PPS database.
    #>

    [CmdletBinding()]
    [OutputType([hashtable])]
    [OutputType([Boolean])]
    param(
        [Parameter(Mandatory=$true)][string]$RestServer,
        [Parameter(Mandatory=$true)][string]$TableName,
        [Parameter(Mandatory=$true)][int]$ID
    )
    if (Test-Connection -Count 1 $RestServer -Quiet) {
        try
        {
            $TableName = $TableName.ToLower()
            Write-LogLevel -Message "Performing Shutdown Tasks for Wman: $ID Table: $TableName" -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel DEBUG
            Invoke-CancelRunningTaskSet -RestServer $RestServer -TableName $TableName -ID $ID
            Invoke-Wait -Seconds 5
            Invoke-QueueAssignedTaskSet -RestServer $RestServer -TableName $TableName -ID $ID
            Invoke-Wait -Seconds 5
            Invoke-CancelStagedTaskSet -RestServer $RestServer -TableName $TableName -ID $ID
            Invoke-Wait -Seconds 5
            Invoke-UpdateWmanData -ComponentId $ID -RestServer $RestServer -Column STATUS_ID -Value 1
        }
        catch
        {
            $ErrorMessage = $_.Exception.Message
            $FailedItem = $_.Exception.ItemName        
            Throw "Invoke-WmanShutdownTaskSet: $ErrorMessage $FailedItem"
        }
        $ReturnMessage
    } else {
        Throw "Invoke-WmanShutdownTaskSet: Unable to reach Rest server: $RestServer."
    }

}
    
# .\PembrokePSwman\private\Invoke-WmanStartupTaskSet.ps1
function Invoke-WmanStartupTaskSet {
    <#
    .DESCRIPTION
        This function will perform shutdown tasks for a Workflow_Manager
    .PARAMETER RestServer
        A RestServer is Required.
    .PARAMETER TableName
        A properties path is Required.
    .PARAMETER ID
        An ID is Required.
    .EXAMPLE
        Invoke-WmanStartupTaskSet -RestServer localhost -TableName tasks -ID 1
    .NOTES
        This will return a hashtable of data from the PPS database.
    #>

    [CmdletBinding()]
    [OutputType([hashtable])]
    [OutputType([Boolean])]
    param(
        [Parameter(Mandatory=$true)][string]$RestServer,
        [Parameter(Mandatory=$true)][string]$TableName,
        [Parameter(Mandatory=$true)][int]$ID
    )
    if (Test-Connection -Count 1 $RestServer -Quiet) {
        try
        {
            $TableName = $TableName.ToLower()
            Write-LogLevel -Message "Performing Startup tasks for Wman: $ID, Table: $TableName" -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel DEBUG
            Invoke-CancelRunningTaskSet -RestServer $RestServer -TableName $TableName -ID $ID
            Invoke-Wait -Seconds 5
            Invoke-CancelStagedTaskSet -RestServer $RestServer -TableName $TableName -ID $ID
            Invoke-Wait -Seconds 5
            Invoke-UpdateWmanData -ComponentId $ID -RestServer $RestServer -Column STATUS_ID -Value 2
        }
        catch
        {
            $ErrorMessage = $_.Exception.Message
            $FailedItem = $_.Exception.ItemName        
            Throw "Invoke-WmanStartupTaskSet: $ErrorMessage $FailedItem"
        }
        $ReturnMessage
    } else {
        Throw "Invoke-WmanStartupTaskSet: Unable to reach Rest server: $RestServer."
    }
}
    
# .\PembrokePSwman\private\Start-AssignedTask.ps1
function Start-AssignedTask {
    <#
    .DESCRIPTION
        This function will gather Status information from PembrokePS web/rest for a Queue_Manager
    .PARAMETER RestServer
        A Rest Server is required.
    .PARAMETER TaskId
        A TaskId is required.
    .EXAMPLE
        Start-AssignedTask -RestServer -localhost -TaskId $TaskId
    .NOTES
        This will return a hashtable of data from the PPS database.
    #>

    [CmdletBinding(
        SupportsShouldProcess = $true,
        ConfirmImpact = "Low"
    )]
    [OutputType([hashtable])]
    [OutputType([boolean])]
    param(
        [Parameter(Mandatory=$true)][string]$RestServer,
        [String]$TableName="tasks",
        [Parameter(Mandatory=$true)][Int]$TaskId
    )
    begin {
        if (Test-Connection -Count 1 $RestServer -Quiet) {
            # No Action needed if the RestServer can be reached.
        } else {
            Throw "Start-AssignedTask: Unable to reach Rest server: $RestServer."
        }
    }
    process
    {
        if ($pscmdlet.ShouldProcess("Creating Headers."))
        {
            try
            {
                #Going to be creating a new record here, need to figure out the 'joins' to ensure the data is good.
                $ExecutionWrapperPath = $SystemRoot + "\wman\bin\Invoke-ExecuteTask.ps1"
                Write-LogLevel -Message "Starting task: $TaskId with Parent path: $ExecutionWrapperPath, PropertyFilePath: $PropertyFilePath" -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel INFO
                Start-Process -WindowStyle Normal powershell.exe -ArgumentList "-file $ExecutionWrapperPath", "-PropertyFilePath $PropertyFilePath -RestServer $RestServer -TableName $TableName -TaskId $TaskId"
            }
            catch
            {
                $ErrorMessage = $_.Exception.Message
                $FailedItem = $_.Exception.ItemName        
                Throw "Start-AssignedTask: $ErrorMessage $FailedItem"
            }
        }
        else
        {
            # -WhatIf was used.
            return $false
        }
    }
}
Write-Verbose 'Importing from [C:\projects\pembrokepstman\PembrokePSwman\public]'
# .\PembrokePSwman\public\Invoke-RegisterWman.ps1
function Invoke-RegisterWman {
    <#
    .DESCRIPTION
        This function will gather Status information from PembrokePS web/rest for a Queue_Manager
    .PARAMETER RestServer
        A Rest Server is required.
    .PARAMETER Component_Id
        A Component_Id is required.
    .PARAMETER Wman_Type
        A Wman_Type is Optional.
    .PARAMETER LocalDir
        A LocalDir is Optional.
    .EXAMPLE
        Invoke-RegisterWman -RestServer localhost -Component_Id 1 -Wman_Type Primary -LocalDir c:\PembrokePS
    .NOTES
        This will return a hashtable of data from the PPS database.
    #>

    [CmdletBinding()]
    [OutputType([hashtable])]
    param(
        [Parameter(Mandatory=$true)][string]$RestServer,
        [Parameter(Mandatory=$true)][string]$Component_Id,
        [string]$Wman_Type = "Primary",
        [string]$LocalDir = "c:\PembrokePS"
    )
    if (Test-Connection -Count 1 $RestServer -Quiet) {
        try
        {
            # Determine if the specified Component is already Registerred and gather component specific properties
            $ComponentStatus = (Get-ComponentStatus -ComponentType Workflow_Manager -ComponentId $Component_Id -RestServer $RestServer).workflow_manager
            $LOG_FILE = $ComponentStatus.LOG_FILE
            $REGISTRATION_STATUS = $ComponentStatus.REGISTRATION_STATUS_ID
            $WKFLW_PORT_ID = $ComponentStatus.WKFLW_PORT_ID
            $RunLogLevel = "CONSOLEONLY"

            if($REGISTRATION_STATUS -eq 13){
                # Update the Registration status
                Invoke-UpdateWmanData -ComponentId $Component_Id -RestServer $RestServer -Column REGISTRATION_STATUS_ID -Value 7

                # Get Component Endpoint Port
                $EndpointPortData = (Get-EndpointPort -RestServer $RestServer -EndpointPortID $WKFLW_PORT_ID).endpoint_ports
                $Port = $EndpointPortData.PORT
                
                # Get System properties from Rest Server -> in pembrokepsRest
                $PropertyData = (Get-PpsPropertySet -RestServer $RestServer).properties
                $RequiredModuleSet = ($PropertyData | Where-Object {$_.PROP_NAME -eq "system.RequiredModules"}).PROP_VALUE
                $BaseWorkingDirectory = ($PropertyData | Where-Object {$_.PROP_NAME -eq "system.Root"}).PROP_VALUE
                $LogDirectory = ($PropertyData | Where-Object {$_.PROP_NAME -eq "system.LogDirectory"}).PROP_VALUE
                $ResultsDirectory = ($PropertyData | Where-Object {$_.PROP_NAME -eq "system.ResultsDirectory"}).PROP_VALUE
                $RunLogLevel = ($PropertyData | Where-Object {$_.PROP_NAME -eq "system.RunLogLevel"}).PROP_VALUE

                # Import required Modules -> in pembrokepsrest
                $RequiredModuleList = $RequiredModuleSet.split(",")
                Invoke-InstallRequiredModuleSet -RequiredModuleSet $RequiredModuleSet

                foreach($RequiredModule in $RequiredModuleList){
                    Get-Module -ListAvailable $RequiredModule | Import-Module
                }

                # Setup the local File directories
                if(Test-Path -Path "$BaseWorkingDirectory\wman") {
                    Write-LogLevel -Message "Directory: $BaseWorkingDirectory, exists." -Logfile "$LOG_FILE" -RunLogLevel CONSOLEONLY -MsgLevel CONSOLEONLY
                } else {
                    Write-LogLevel -Message "Creating \wman\data and \wman\logs Directories." -Logfile "$LOG_FILE" -RunLogLevel CONSOLEONLY -MsgLevel CONSOLEONLY
                    New-Item -Path "$BaseWorkingDirectory\wman\data" -ItemType Directory
                    New-Item -Path "$BaseWorkingDirectory\wman\logs" -ItemType Directory
                }
                Invoke-DeployPPSRest
                $WmanRoutesDestination = $BaseWorkingDirectory + "\wman\data"
                $WmanEndpointRoutes = $BaseWorkingDirectory + "\wman\data\WmanEndpointRoutes.ps1"
                # Still need to get this file there!
                $Source=(Split-Path -Path (Get-Module -ListAvailable PembrokePSwman).path)
                $WmanEndpointRoutesSource = $Source + "\data\WmanEndpointRoutes.ps1"
                Write-LogLevel -Message "Copying Properties file to $BaseWorkingDirectory\wman\data" -Logfile "$LOG_FILE" -RunLogLevel CONSOLEONLY -MsgLevel CONSOLEONLY
                Copy-Item -Path "$Source\scripts" -Destination "$BaseWorkingDirectory\wman\data" -Container -Recurse -Confirm:$false       
                Copy-Item -Path "$Source\bin" -Destination "$BaseWorkingDirectory\wman\bin" -Container -Recurse -Confirm:$false
                Copy-Item -Path "$WmanEndpointRoutesSource" -Destination $WmanRoutesDestination -Confirm:$false -Force
                
                # Write Properties file -> In utilities
                Write-LogLevel -Message "Creating Local properties file" -Logfile "$LOG_FILE" -RunLogLevel CONSOLEONLY -MsgLevel CONSOLEONLY
                $PropertiesFile = "c:\PembrokePS\wman\pembrokeps.properties"
                $wLogDirectory = $LogDirectory.replace('\','\\')
                $wResultsDirectory = $ResultsDirectory.replace('\','\\')
                $wBaseWorkingDirectory = $BaseWorkingDirectory.replace('\','\\')
                $wLOG_FILE = $LOG_FILE.replace('\','\\')
                $wWmanEndpointRoutes = $WmanEndpointRoutes.replace('\','\\')

                Write-Output "system.RestServer=$RestServer" | Out-File $PropertiesFile
                Write-Output "system.LogDirectory=$wLogDirectory" | Out-File $PropertiesFile -Append
                Write-Output "system.ResultsDirectory=$wResultsDirectory" | Out-File $PropertiesFile -Append
                Write-Output "system.Root=$wBaseWorkingDirectory" | Out-File $PropertiesFile -Append
                Write-Output "component.Id=$Component_Id" | Out-File $PropertiesFile -Append
                Write-Output "component.Type=Workflow_Manager" | Out-File $PropertiesFile -Append
                Write-Output "component.RestPort=$Port" | Out-File $PropertiesFile -Append
                Write-Output "component.RunLogLevel=$RunLogLevel" | Out-File $PropertiesFile -Append
                Write-Output "component.logfile=$wLOG_FILE" | Out-File $PropertiesFile -Append
                Write-Output "component.WmanEndpointRoutes=$wWmanEndpointRoutes" | Out-File $PropertiesFile -Append
            }
            else 
            {
                Throw "Wman Component ID: $Component_Id is not Available to Register."
            }
        }
        catch
        {
            $ErrorMessage = $_.Exception.Message
            $FailedItem = $_.Exception.ItemName        
            Throw "Invoke-RegisterWman: $ErrorMessage $FailedItem"
        }
        $PropertiesFileData
    } else {
        Throw "Invoke-RegisterWman: Unable to reach web server."
    }
    
}
# .\PembrokePSwman\public\Invoke-Wman.ps1
function Invoke-Wman {
    <#
    .DESCRIPTION
        This function will gather Status information from PembrokePS web/rest for a Workflow_Manager
    .PARAMETER PropertyFilePath
        A properties path is Required.
    .EXAMPLE
        Invoke-Wman -PropertyFilePath "c:\PembrokePS\Wman\pembrokeps.properties"
    .NOTES
        This will return a hashtable of data from the PPS database.
    #>

    [CmdletBinding()]
    [OutputType([hashtable])]
    [OutputType([Boolean])]
    param(
        [Parameter(Mandatory=$true)][string]$PropertyFilePath
    )
    if (Test-Path -Path $PropertyFilePath) {
        # Gather Local Properties for the Workflow Manager
        $PpsProperties = Get-LocalPropertySet -PropertyFilePath $PropertyFilePath
        $RestServer = $PpsProperties.'system.RestServer'
        $SystemRoot = $PpsProperties.'system.root'
        $ID = $PpsProperties.'component.Id'
        $RunLogLevel = $PpsProperties.'component.RunLogLevel'
        $LOG_FILE = $PpsProperties.'component.logfile'
        Write-LogLevel -Message "Gathering Local Properties from: $PropertyFilePath, SystemRoot: $SystemRoot." -Logfile $LOG_FILE -RunLogLevel CONSOLEONLY -MsgLevel CONSOLEONLY
    } else {
        Write-LogLevel -Message "Unable to Locate Local properties file: $PropertyFilePath." -Logfile $LOG_FILE -RunLogLevel CONSOLEONLY -MsgLevel CONSOLEONLY
        Throw "Invoke-Wman: Unable to Locate Properties file."
    }
    try
    {
        $script:WmanRunning = "Running"
        do {
            # Test connection with the Database Server
            Write-LogLevel -Message "Starting Invoke-Wman loop" -Logfile $LOG_FILE -RunLogLevel $RunLogLevel -MsgLevel INFO
            if (Test-Connection -Count 1 $RestServer -Quiet) {
                # No Action needed if the RestServer can be reached.
                $Host.UI.RawUI.WindowTitle = "Workflow_Manager WmanId:$ID"
            } else {
                $script:WmanRunning = "Shutdown"
                Write-LogLevel -Message "Unable to reach RestServer: $RestServer." -Logfile $LOG_FILE -RunLogLevel $RunLogLevel -MsgLevel ERROR
                Throw "Invoke-Wman: Unable to reach Rest server: $RestServer."
            }
            Write-LogLevel -Message "Validated Connection to RestServer: $RestServer." -Logfile $LOG_FILE -RunLogLevel $RunLogLevel -MsgLevel INFO 
            # Get the Status and Workflow Manager Specific Information from the Database
            $WmanStatusData = Get-WmanStatus -ComponentId $ID -RestServer $RestServer
            $WorkflowManagerStatus = $WmanStatusData.STATUS_ID
            $LOG_FILE = $WmanStatusData.LOG_FILE
            $ManagerWait = $WmanStatusData.WAIT
            $MAX_CONCURRENT_TASKS = $WmanStatusData.MAX_CONCURRENT_TASKS
            $WORKFLOW_MANAGER_TYPE_ID = $WmanStatusData.WORKFLOW_MANAGER_TYPE_ID
            Write-LogLevel -Message "Get-WmanStatus is complete" -Logfile $LOG_FILE -RunLogLevel $RunLogLevel -MsgLevel DEBUG 
            $TableNameData = Get-WmanTableName -RestServer $RestServer -Type_ID $WORKFLOW_MANAGER_TYPE_ID
            $TableName = ($TableNameData).TABLENAME
            Write-LogLevel -Message "Get WmanTablename is complete, TableName: $TableName" -Logfile $LOG_FILE -RunLogLevel $RunLogLevel -MsgLevel INFO
            # Based on the Status Perform Specific actions
            Write-LogLevel -Message "WorkflowManager ID: $ID" -Logfile $LOG_FILE -RunLogLevel $RunLogLevel -MsgLevel INFO 
            Write-LogLevel -Message "WorkflowManager Status: $WorkflowManagerStatus" -Logfile $LOG_FILE -RunLogLevel $RunLogLevel -MsgLevel INFO 
            Write-LogLevel -Message "WorkflowManager TableName : $TableName" -Logfile $LOG_FILE -RunLogLevel $RunLogLevel -MsgLevel INFO 
            Write-LogLevel -Message "WorkflowManager Wait: $ManagerWait" -Logfile $LOG_FILE -RunLogLevel $RunLogLevel -MsgLevel INFO 
            Write-LogLevel -Message "WorkflowManager MAX_CONCURRENT_TASKS: $MAX_CONCURRENT_TASKS" -Logfile $LOG_FILE -RunLogLevel $RunLogLevel -MsgLevel INFO 
            Write-LogLevel -Message "WorkflowManager LogFile: $LOG_FILE" -Logfile $LOG_FILE -RunLogLevel $RunLogLevel -MsgLevel INFO 
            if ($WorkflowManagerStatus -eq 1) {
                # Down - Not doing Anything
                Write-LogLevel -Message "Get-WmanStatus is Down, Not taking Action." -Logfile $LOG_FILE -RunLogLevel $RunLogLevel -MsgLevel ERROR 
            } elseif ($WorkflowManagerStatus -eq 2) {
                # Up - Perform normal Tasks
                Write-LogLevel -Message "Get-WmanStatus is UP, performing Normal Operations" -Logfile $LOG_FILE -RunLogLevel $RunLogLevel -MsgLevel INFO 
                Write-LogLevel -Message "Reviewing Assigned Tasks" -Logfile $LOG_FILE -RunLogLevel $RunLogLevel -MsgLevel INFO 
                Invoke-ReviewAssignedTaskSet -RestServer $RestServer -TableName $TableName -MAX_CONCURRENT_TASKS $MAX_CONCURRENT_TASKS -ID $ID
                Write-LogLevel -Message "Normal Operations Completed." -Logfile $LOG_FILE -RunLogLevel $RunLogLevel -MsgLevel DEBUG 
            } elseif ($WorkflowManagerStatus -eq 3) {
                # Starting Up - Perform startup Tasks
                Write-LogLevel -Message "Performting Startup Tasks" -Logfile $LOG_FILE -RunLogLevel $RunLogLevel -MsgLevel INFO 
                Invoke-WmanStartupTaskSet -TableName $TableName -RestServer $RestServer -ID $ID
                Write-LogLevel -Message "Startup Tasks Completed." -Logfile $LOG_FILE -RunLogLevel $RunLogLevel -MsgLevel DEBUG
            } elseif ($WorkflowManagerStatus -eq 4) {
                # Shutting Down - Perform Shutdown Tasks
                Write-LogLevel -Message "Performing Shutdown tasks." -Logfile $LOG_FILE -RunLogLevel $RunLogLevel -MsgLevel INFO 
                Invoke-WmanShutdownTaskSet -TableName $TableName -RestServer $RestServer -ID $ID
                $script:WmanRunning = "Shutdown"
                Write-LogLevel -Message "Shutdown tasks completed." -Logfile $LOG_FILE -RunLogLevel $RunLogLevel -MsgLevel INFO 
            }
            Write-LogLevel -Message "Manager running String: $script:WmanRunning" -Logfile $LOG_FILE -RunLogLevel $RunLogLevel -MsgLevel DEBUG 
            if($script:WmanRunning -ne "Shutdown"){
                Write-LogLevel -Message "Waiting $ManagerWait Seconds" -Logfile $LOG_FILE -RunLogLevel $RunLogLevel -MsgLevel INFO 
                Invoke-Wait -Seconds $ManagerWait
            }
        } while ($script:WmanRunning -ne "Shutdown")
        Write-LogLevel -Message "Exiting WorkflowManager Function." -Logfile $LOG_FILE -RunLogLevel $RunLogLevel -MsgLevel INFO 
    }
    catch
    {
        $ErrorMessage = $_.Exception.Message
        $FailedItem = $_.Exception.ItemName        
        Throw "Invoke-Wman: $ErrorMessage $FailedItem"
    }
    
}
# .\PembrokePSwman\public\Invoke-WmanKicker.ps1
function Invoke-WmanKicker {   
   <#
    .DESCRIPTION
        This Script runs in the background of the Workflow manager to help with health/mgmt of the component.
    .PARAMETER PropertyFilePath
        A properties path is Required.
    .EXAMPLE
        Invoke-WmanKicker -PropertyFilePath "c:\PembrokePS\Wman\pembrokeps.properties"
    .NOTES
        Nothing to see here.
    #>

    [CmdletBinding()]
    [OutputType([Boolean])]
    param(
        [Parameter(Mandatory=$true)][string]$PropertyFilePath
    )
    if (Test-Path -Path $PropertyFilePath) {
        # Gather Local Properties for the Workflow Manager
        $PpsProperties = Get-LocalPropertySet -PropertyFilePath $PropertyFilePath
        $RestServer = $PpsProperties.'system.RestServer'
        $SystemRoot = $PpsProperties.'system.root'
        $ID = $PpsProperties.'component.Id'
        $LOG_FILE = $PpsProperties.'component.logfile'
        $Port = $PpsProperties.'component.RestPort'
        $AvailableRoutesFile.'component.AvailableRoutesFile'
        $RunLogLevel = "CONSOLEONLY"
        Write-LogLevel -Message "Gathering Local Properties from: $PropertyFilePath, SystemRoot: $SystemRoot. $RunLogLevel" -Logfile $LOG_FILE -RunLogLevel CONSOLEONLY -MsgLevel CONSOLEONLY
    } else {
        Write-LogLevel -Message "Unable to Locate Local properties file: $PropertyFilePath." -Logfile $LOG_FILE -RunLogLevel CONSOLEONLY -MsgLevel CONSOLEONLY
        Throw "Invoke-WmanKicker: Unable to Locate Properties file."
    }

    try
    {
        $script:WmanKickerRunning = "Running"
        do {
            # Test connection with the Database Server
            Write-LogLevel -Message "Starting Invoke-WmanKicker loop" -Logfile $LOG_FILE -RunLogLevel CONSOLEONLY -MsgLevel INFO
            if (Test-Connection -Count 1 $RestServer -Quiet) {
                $Host.UI.RawUI.WindowTitle = "WmanKicker WmanId:$ID"
            } else {
                $script:WmanKickerRunning = "Shutdown"
                Write-LogLevel -Message "Unable to reach RestServer: $RestServer." -Logfile $LOG_FILE -RunLogLevel CONSOLEONLY -MsgLevel ERROR
                Throw "Invoke-Wman: Unable to reach Rest server: $RestServer."
            }
            Write-LogLevel -Message "Validated Connection to RestServer: $RestServer." -Logfile $LOG_FILE -RunLogLevel CONSOLEONLY -MsgLevel INFO 

            # Get the Status and Workflow Manager Specific Information from the Database
            $WmanStatusData = Get-WmanStatus -ComponentId $ID -RestServer $RestServer
            $WorkflowManagerStatus = $WmanStatusData.STATUS_ID
            $ManagerWait = $WmanStatusData.WAIT

            Write-LogLevel -Message "Get-WmanStatus is complete" -Logfile $LOG_FILE -RunLogLevel CONSOLEONLY -MsgLevel DEBUG 
            # Based on the Status Perform Specific actions
            Write-LogLevel -Message "WorkflowManager ID: $ID" -Logfile $LOG_FILE -RunLogLevel CONSOLEONLY -MsgLevel INFO 
            Write-LogLevel -Message "WorkflowManager Status: $WorkflowManagerStatus" -Logfile $LOG_FILE -RunLogLevel CONSOLEONLY -MsgLevel INFO 
            Write-LogLevel -Message "WorkflowManager Wait: $ManagerWait" -Logfile $LOG_FILE -RunLogLevel CONSOLEONLY -MsgLevel INFO 

            # Check Wman Endpoint
            If(Get-PpsProcessStatus -ProcessName "Port:$Port"){
                Write-LogLevel -Message "Wman Endpoint is running." -Logfile $LOG_FILE -RunLogLevel CONSOLEONLY -MsgLevel ERROR
            } else {
                # Start the Endpoint
                $SourceAvailableRoutesFile = $SystemRoot + "\wman\data\WmanEndpointRoutes.ps1"
                Invoke-StartPPSEndpoint -Port $Port -SourceAvailableRoutesFile $SourceAvailableRoutesFile
            }
            if ($WorkflowManagerStatus -eq 1) {
                # Down - Not doing Anything.
                Write-LogLevel -Message "Get-WmanStatus is Down, Not taking Action." -Logfile $LOG_FILE -RunLogLevel CONSOLEONLY -MsgLevel ERROR 
            } elseif ($WorkflowManagerStatus -eq 2) {
                # Up - Not doing anything.
                Write-LogLevel -Message "Get-WmanStatus is Up, Not taking Action." -Logfile $LOG_FILE -RunLogLevel CONSOLEONLY -MsgLevel ERROR 
            } elseif ($WorkflowManagerStatus -eq 3) {
                # Starting Up - Perform startup Tasks
                Write-LogLevel -Message "Starting Up the Workflow Manager" -Logfile $LOG_FILE -RunLogLevel CONSOLEONLY -MsgLevel INFO 
                # Start a new Window, then start the Invoke-Wman Function.
                $ExecutionPath = $SystemRoot + "\wman\bin\Invoke-NewConsole.ps1"
                # Check that the wman Process is not running
                If(Get-PpsProcessStatus -ProcessName WorkFlow_Manager){
                    Write-LogLevel -Message "Workflow Manager is running." -Logfile $LOG_FILE -RunLogLevel CONSOLEONLY -MsgLevel ERROR
                } else {
                    # Start the Workflow Manager
                    Write-LogLevel -Message "Starting path: $ExecutionPath, PropertyFilePath: $PropertyFilePath, -FunctionName Invoke-Wman" -Logfile "$LOG_FILE" -RunLogLevel CONSOLEONLY -MsgLevel INFO
                    Start-Process -WindowStyle Normal powershell.exe -ArgumentList "-file $ExecutionPath", "-PropertyFilePath $PropertyFilePath -FunctionName Invoke-Wman"
                    Write-LogLevel -Message "Workflow Manager Has been started. Giving the Manager 5min to start." -Logfile $LOG_FILE -RunLogLevel CONSOLEONLY -MsgLevel DEBUG
                    Invoke-Wait -Seconds 300
                }
            } elseif ($WorkflowManagerStatus -eq 4) {
                # Shutting Down - Not doing anything.
                Write-LogLevel -Message "Get-WmanStatus is Shutdown, not taking action." -Logfile $LOG_FILE -RunLogLevel CONSOLEONLY -MsgLevel INFO 
            }
            Write-LogLevel -Message "ManagerKicker is running, Waiting $ManagerWait, before checking status again." -Logfile $LOG_FILE -RunLogLevel CONSOLEONLY -MsgLevel DEBUG 
            Invoke-Wait -Seconds $ManagerWait
        } while ($script:WmanKickerRunning -ne "Shutdown")
        Write-LogLevel -Message "Exiting WorkflowManager Kicker Script" -Logfile $LOG_FILE -RunLogLevel CONSOLEONLY -MsgLevel INFO 
    }
    catch
    {
        $ErrorMessage = $_.Exception.Message
        $FailedItem = $_.Exception.ItemName        
        Throw "Invoke-WmanKicker: $ErrorMessage $FailedItem"
    }
}

# .\PembrokePSwman\public\Invoke-WorkflowWrapper.ps1
function Invoke-WorkflowWrapper {
    <#
    .DESCRIPTION
        This Script will Execute a specified task, and generate any needed subtasks.
    .PARAMETER PropertyFilePath
        A Rest PropertyFilePath is required.
    .PARAMETER TaskId
        A TaskId is required.
    .EXAMPLE
        Invoke-WorkflowWrapper -PropertyFilePath "c:\PembrokePS\Wman\data\pembrokeps.properties" -TaskId 1 -RestServer localhost -TableName tasks
    .NOTES
        This will execute a task against a specific target defined in the PembrokePS database.
    #>

    param(
        [Parameter(Mandatory=$true)][string]$PropertyFilePath,
        [String]$TableName="tasks",
        [Parameter(Mandatory=$true)][Int]$TaskId,
        [Parameter(Mandatory=$true)][string]$RestServer
    )
    begin {
        if (Test-Connection -Count 1 $RestServer -Quiet) {
            # No Action needed if the RestServer can be reached.
        } else {
            Throw "Workflow_Wrapper: Unable to reach web server."
        }
        if (Test-Path -Path $PropertyFilePath) {
            # Gather Local Properties for the Workflow Manager
            $PpsProperties = Get-LocalPropertySet -PropertyFilePath $PropertyFilePath
            $RestServer = $PpsProperties.'system.RestServer'
            $RunLogLevel = $PpsProperties.'component.RunLogLevel'
            $BaseWorkingDirectory = $PpsProperties.'system.Root'
            $WmanId = $PpsProperties.'component.Id'
            $ResultsDirectory = $PpsProperties.'system.LogDirectory'
            # Create Logfile Path
            $LOG_FILE = $ResultsDirectory + "\Task_$TaskId" + ".log"
            Write-LogLevel -Message "Gathering Local Properties from: $PropertyFilePath" -Logfile $LOG_FILE -RunLogLevel CONSOLEONLY -MsgLevel CONSOLEONLY
        } else {
            Write-LogLevel -Message "Unable to Locate Local properties file: $PropertyFilePath." -Logfile $LOG_FILE -RunLogLevel CONSOLEONLY -MsgLevel CONSOLEONLY
            Throw "Workflow_Wrapper: Unable to Locate Properties file."
        }     
        # Import Required Modules
        Write-LogLevel -Message "Importing Additional Required Modules." -Logfile $LOG_FILE -RunLogLevel CONSOLEONLY -MsgLevel CONSOLEONLY
        Invoke-ImportWmanModuleSet -RestServer $RestServer -WmanId $WmanId
        # Get all the Task Information.
        Write-LogLevel -Message "Gathering information for task: $TaskId" -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel DEBUG
        $TaskData = Get-TaskInfo -TaskId $TaskId -TableName $TableName -RestServer $RestServer
        
        # Set the task to running
        $body = @{STATUS_ID = "8"
                    RESULT_ID = "6"
                    LOG_FILE = "$LOG_FILE"
                }
        Write-LogLevel -Message "Setting Task: $TaskId to Running(8)" -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel INFO
        Invoke-UpdateTaskTable -RestServer $RestServer -TableName $TableName -TaskID $TaskId -Body $body
    }
    process
    {
        try
        {
            # Gather Specific task info
            $Task_Path = ($TaskData.task_types).TASK_PATH
            $Task_Args = ($TaskData).ARGUMENTS
            $Target_ID = ($TaskData).TARGET_ID
            $Target_Name = ($TaskData.targets).TARGET_NAME
            $Target_IP = ($TaskData.targets).IP_ADDRESS
            $TASK_TYPE_ID = ($TaskData).TASK_TYPE_ID
            # Set a place holder
            $script:TaskResult = 4
            # Build the Execution Path
            $ExecutionPath = $BaseWorkingDirectory + "\wman\scripts\" + $Task_Path
            # Validate the Path Exists and Perform the task.
            Write-LogLevel -Message "Target ID: $Target_ID, Target: $Target_Name, IP: $Target_IP" -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel DEBUG
            Write-LogLevel -Message "Executing Script: $ExecutionPath, with Args: $Task_Args" -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel DEBUG
            Invoke-ExecutionPath -ExecutionPath $ExecutionPath
            # Update the Database with the result
            $body = @{STATUS_ID = "9"
                        RESULT_ID = "$script:TaskResult"
                        LOG_FILE = "$LOG_FILE"
                }
            Write-LogLevel -Message "Setting Task: $TaskId to Complete(9) and Result: $script:TaskResult" -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel INFO
            Invoke-UpdateTaskTable -RestServer $RestServer -TableName $TableName -TaskID $TaskId -Body $body
            # Run SubTask Generator
            $SubTaskData = (Get-SubTaskData -Task_Type_Id $TASK_TYPE_ID -RestServer $RestServer).subtask_generator
            if($script:TaskResult -eq 1){
                $SubTaskId = (Invoke-GenerateSubTask -RestServer $RestServer -SubTaskTypeId ($SubTaskData.PASS_SUBTASK_ID) -TableName $TableName -Target_ID $Target_ID).NewTaskId
            } elseif($script:TaskResult -eq 2){
                $SubTaskId = (Invoke-GenerateSubTask -RestServer $RestServer -SubTaskTypeId ($SubTaskData.FAIL_SUBTASK_ID) -TableName $TableName -Target_ID $Target_ID).NewTaskId
            } else {
                $SubTaskId = "No SubTask"
            }
            Write-LogLevel -Message "Generated taskid: $SubTaskId" -Logfile "$LOG_FILE" -RunLogLevel $RunLogLevel -MsgLevel INFO
        }
        catch
        {
            $ErrorMessage = $_.Exception.Message
            $FailedItem = $_.Exception.ItemName        
            Throw "Invoke-WorkflowWrapper: $ErrorMessage $FailedItem"
        }
    }
}
# .\PembrokePSwman\public\Start-Wman.ps1
function Start-Wman {
    <#
    .DESCRIPTION
        This function will gather Status information from PembrokePS web/rest for a Queue_Manager
    .PARAMETER RestServer
        A Rest Server is required.
    .PARAMETER PropertyFilePath
        A PropertyFilePath is required.
    .EXAMPLE
        Start-Wman -RestServer -localhost
    .NOTES
        This will return a hashtable of data from the PPS database.
    #>

    [CmdletBinding(
        SupportsShouldProcess = $true,
        ConfirmImpact = "Low"
    )]
    [OutputType([hashtable])]
    [OutputType([boolean])]
    param(
        [Parameter(Mandatory=$true)][string]$RestServer,
        [Parameter(Mandatory=$true)][string]$PropertyFilePath
    )
    begin {
        if (Test-Connection -Count 1 $RestServer -Quiet) {
            # No Action needed if the RestServer can be reached.
        } else {
            Throw "Start-Wman: Unable to reach web server."
        }
        if (Test-Path -Path $PropertyFilePath) {
            # Gather Local Properties for the Workflow Manager
            $PpsProperties = Get-LocalPropertySet -PropertyFilePath $PropertyFilePath
            $RestServer = $PpsProperties.'system.RestServer'
            $ResultsDirectory = $PpsProperties.'system.LogDirectory'
            $SystemRoot = $PpsProperties.'system.Root'
            # Create Logfile Path
            $LOG_FILE = $ResultsDirectory + "\Task_$TaskId" + ".log"
            Write-LogLevel -Message "Gathering Local Properties from: $PropertyFilePath" -Logfile $LOG_FILE -RunLogLevel CONSOLEONLY -MsgLevel CONSOLEONLY
        } else {
            Write-LogLevel -Message "Unable to Locate Local properties file: $PropertyFilePath." -Logfile $LOG_FILE -RunLogLevel CONSOLEONLY -MsgLevel CONSOLEONLY
            Throw "Start-Wman: Unable to Locate Properties file."
        } 
    }
    process
    {
        if ($pscmdlet.ShouldProcess("Performing Start-Wman."))
        {
            try
            {
                Write-LogLevel -Message "lamp" -Logfile "$LOG_FILE" -RunLogLevel CONSOLEONLY -MsgLevel CONSOLEONLY
                If(Get-PpsProcessStatus -ProcessName WmanKicker){
                    Write-LogLevel -Message "WmanKicker is running." -Logfile $LOG_FILE -RunLogLevel CONSOLEONLY -MsgLevel ERROR
                } else {
                    # Start the Process
                    $ExecutionWrapperPath = $SystemRoot + "\wman\bin\Invoke-NewConsole.ps1"
                    Write-LogLevel -Message "Starting Wman Kicker Process $ExecutionWrapperPath" -Logfile "$LOG_FILE" -RunLogLevel CONSOLEONLY -MsgLevel INFO
                    Start-Process -WindowStyle Normal powershell.exe -ArgumentList "-file $ExecutionWrapperPath", "-FunctionName Invoke-WmanKicker -PropertyFilePath $PropertyFilePath"
                }
            }
            catch
            {
                $ErrorMessage = $_.Exception.Message
                $FailedItem = $_.Exception.ItemName        
                Throw "Start-Wman: $ErrorMessage $FailedItem"
            }
        }
        else
        {
            # -WhatIf was used.
            return $false
        }
    }
}
Write-Verbose 'Importing from [C:\projects\pembrokepstman\PembrokePSwman\classes]'