PoshBPA.psm1

# Load module functions
Get-ChildItem -Path "$PSScriptRoot\Scripts\*.ps1" | ForEach-Object {
    . $_.FullName
    Export-ModuleMember -Function $_.BaseName
}
# Load utility functions
Get-ChildItem -Path "$PSScriptRoot\Utility\*.ps1" | ForEach-Object {
    . $_.FullName
}

Set-Variable -Name BPAScheduleDateFormat -Value "MM/dd/yyyy HH:mm:ss" -Scope Global
Set-Variable -Name BPAGuidRegex -Value "^(\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\}{0,1})$" -Scope Global

#region Construct Types
enum BPAConstructType {
    Undefined         = 0
    Folder            = 1
    Task              = 2
    Workflow          = 3
    Condition         = 4
    RootContainer     = 5
    UserPreference    = 7
    Agent             = 8
    MachineConnection = 9
    User              = 10
    AgentGroup        = 11
    UserGroup         = 12
    Evaluation        = 13
    Comment           = 14
    AuditEvent        = 16
    ExecutionEvent    = 17
    Connection        = 18
    Wait              = 19
    Joiner            = 20
    Exclusion         = 21
    ServerProperty    = 22
    WorkflowProperty  = 23
    AgentProperty     = 24
    TaskProperty      = 25
    Constant          = 26
    Package           = 27
    BPASystem         = 30
    Permission        = 34
    SystemPermission  = 35
    Process           = 40
    WorkflowItemProperty = 46
    WorkflowItem      = 47
    WorkflowTrigger   = 470 # Also 47, but we only use this in Get-BPAObjectType
    WorkflowLink      = 48
    WorkflowVariable  = 49
    ExecutionServerProperty = 50
    ManagementServerProperty = 51
    ManagedTaskProperty = 54
    Snapshot          = 58
    ExclusionPeriod   = 61
    SnapshotInfo      = 63
    Notification      = 64
    Instance          = 65
    ApiPermission     = 66
    SNMPCredential    = 67
    WindowsControl    = 68
}

enum BPATriggerType {
    All         = -1
    Logon       = 1
    Window      = 2
    Schedule    = 3
    Keyboard    = 4
    Idle        = 5
    Performance = 6
    EventLog    = 7
    FileSystem  = 8
    Process     = 9
    Service     = 10
    SNMPTrap    = 11
    WMI         = 12
    Time        = 13
    Database    = 14
    SharePoint  = 15
}

enum BPAAgentType {
    All          = -1
    Unknown      = 0
    TaskAgent    = 1
    ProcessAgent = 2
}
#endregion

#region Workflow types
enum BPAWorkflowVarType {
    Auto   = 1
    Text   = 2
    Number = 3
}

enum BPALinkType {
    Blank   = 1
    Success = 2
    Failure = 3
    Result  = 4
}

enum BPALinkResultType {
    Default = 0
    True    = 1
    False   = 2
    Value   = 3
}

enum BPAWorkflowVarDataType {
    Variable = 1
    Array    = 2
    Dataset  = 3
}
#endregion

#region Task types
enum BPATaskFailureAction {
    Success = 1
    Failure = 2
    ReturnResult = 3
}

enum BPATaskIsolation {
    Default = 0
    Always  = 1
    Never   = 2
}

enum BPAConcurrencyType {
    AlwaysRun                      = 1
    RunningInstancesBelowThreshold = 2
    RunningTasksBelowThreshold     = 3
    RunWithNoOtherTasks            = 4
}

enum BPAPriorityAction {
    Hold               = 1
    DoNotRun           = 2
    HoldInterrupt      = 3
    HoldTimeout        = 4
    InterruptTasks     = 5
    InterruptInstances = 6
}
#endregion

#region Process types
enum BPAProcessRunningContext {
    Default = 1
    SH      = 2
    Bash    = 3
}
#endregion

#region Condition types
enum BPAConditionUserMode {
    NoUser        = 1
    DefaultUser   = 2
    SpecifiedUser = 3
}
#endregion

#region Schedule Condition types
enum BPAScheduleType {
    Custom         = 0
    SecondInterval = 1
    MinuteInterval = 2
    HourInterval   = 3
    DayInterval    = 4
    WeekInterval   = 5
    MonthInterval  = 6
    Holidays       = 7
}

enum BPAScheduleMeasure {
    Day       = 0
    WorkDay   = 1
    Monday    = 2
    Tuesday   = 3
    Wednesday = 4
    Thursday  = 5
    Friday    = 6
    Saturday  = 7
    Sunday    = 8
}

enum BPAOnTaskLateRescheduleOption {
    RunImmediately      = 0
    IgnoreAndReschedule = 1
    DisableTrigger      = 3
}

enum BPARescheduleOption {
    RelativeToOriginalTime  = 0
    RelativeToTriggeredTime = 1
    DisableTrigger          = 2
}
#endregion

#region Keyboard Condition types
enum BPAKeyboardConditionKeyType {
    Hotkey = 1
    Text   = 2
}
#endregion

#region Window Condition types
enum BPAWindowAction {
    Open       = 0
    Close      = 1
    Focus      = 2
    Background = 3
}
#endregion

#region Logon Condition types
enum BPALogonAction {
    RunAsLoggedOnUser   = 1
    LogonSpecifiedUser  = 2 # Same as unlock
    RunAsBackgroundUser = 3
    DoNotRun            = 4
}
#endregion

#region Event Log Condition types
enum BPAEventLogTriggerEventType {
    Information  = 0
    Warning      = 1
    Error        = 2
    SuccessAudit = 3
    FailAudit    = 4
    Any          = 5
}
#endregion

#region Database Condition types
enum BPADatabaseTriggerType {
    SQL    = 0
    Oracle = 1
}
#endregion

#region Performance Condition types
enum BPAPerformanceOperator {
    Below = 0
    Above = 1
}
#endregion

#region Process Condition types
enum BPAProcessTriggerState {
    Started           = 1
    Ended             = 2
    StoppedResponding = 3
}
#endregion

#region Service Condition types
enum BPAServiceTriggerState {
    StoppedResponding = 0
    Started           = 1
    Stopped           = 2
    Resumed           = 3
    Paused            = 4
    Installed         = 5
    Removed           = 6
}
#endregion

#region SNMP Condition types
enum BPASnmpGenericType {    
    Any                   = 0
    ColdStart             = 1
    WarmStart             = 2
    LinkDown              = 3
    LinkUp                = 4
    AuthenticationFailure = 5
    EGPNeighborLoss       = 6
    EnterpriseSpecific    = 7
}
#endregion

#region SharePoint Condition types
enum BPASharePointScope {
    Web  = 0
    List = 1
}
#endregion

#region Instance types
enum BPAInstanceStatus {
    All       = -1
    Completed = -2
    Success   = 1
    Failed    = 2
    Aborted   = 3
    Stopped   = 4
    TimedOut  = 7
    Paused    = 9
    Queued    = 11
    Running   = 12
    ResumedFromFailure = 13
    #Error = ?
}
#endregion

#region Generic types
enum BPATimeMeasure {
    Seconds      = 0
    Minutes      = 1
    Hours        = 2
    Days         = 3
    Milliseconds = 4
}
enum BPAEncryptionAlgorithm {
    NoEncryption = 0
    DES          = 1
    AES          = 2
    TripleDES    = 3
}

enum BPACompletionState {
    InDevelopment = 0
    Testing       = 1
    Production    = 2
    Archive       = 3
}
#endregion

enum BPAAuditEventType {
    All = -1

    # Workflow event types
    WorkflowCreated  = 1000
    WorkflowRemoved  = 1001
    WorkflowEdited   = 1002
    WorkflowEnabled  = 1003
    WorkflowDisabled = 1004
    WorkflowRenamed  = 1005
    WorkflowMoved    = 1006
    WorkflowPropertiesModified  = 1007
    WorkflowExported = 1008
    WorkflowImported = 1009
    WorkflowPermissionsModified = 1010

    # Task event types
    TaskCreated  = 1100
    TaskRemoved  = 1101
    TaskEdited   = 1102
    TaskEnabled  = 1103
    TaskDisabled = 1104
    TaskRenamed  = 1105
    TaskMoved    = 1106
    TaskPropertiesModified = 1107
    TaskExported = 1108
    TaskImported = 1109
    TaskPermissionsModified = 1110

    # Condition event types
    ConditionCreated  = 1200
    ConditionRemoved  = 1201
    ConditionEdited   = 1202
    ConditionEnabled  = 1203
    ConditionDisabled = 1204
    ConditionRenamed  = 1205
    ConditionMoved    = 1206
    ConditionPropertiesModified = 1207
    ConditionExported = 1208
    ConditionImported = 1209
    ConditionPermissionsModified = 1210

    # Process event types
    ProcessCreated  = 1900
    ProcessRemoved  = 1901
    ProcessEdited   = 1902
    ProcessEnabled  = 1903
    ProcessDisabled = 1904
    ProcessRenamed  = 1905
    ProcessMoved    = 1906
    ProcessPropertiesModified = 1907
    ProcessExported = 1908
    ProcessImported = 1909
    ProcessPermissionsModified = 1910

    # Agent event types
    AgentConnected            = 300
    AgentDisconnected         = 301
    AgentDisconnectedByServer = 302
    TaskAgentUpgrading        = 303
    TaskAgentConnected        = 304
    ProcessAgentConnected     = 305
    TaskAgentDisconnected     = 308
    ProcessAgentDisconnected  = 309
    AgentRegistered           = 1400
    AgentRemoved              = 1401
    AgentEnabled              = 1402
    AgentDisabled             = 1403
    AgentMoved                = 1404
    AgentPropertiesModified   = 1405
    AgentRenamed              = 1406
    AgentPermissionsModified  = 1407

    # Agent group event types
    AgentGroupCreated  = 1700
    AgentGroupRemoved  = 1701
    AgentGroupEdited   = 1702
    AgentGroupEnabled  = 1703
    AgentGroupDisabled = 1704
    AgentGroupRenamed  = 1705
    AgentGroupMoved    = 1706
    AgentGroupPropertiesModified = 1707
    AgentGroupPermissionsModified = 1708

    # User event types
    UserLoggedOn        = 200
    UserLogonDenied     = 201
    UserLoggedOff       = 202
    UserConnectedSMC    = 306
    UserConnectedWFD    = 307
    UserDisconnectedSMC = 310
    UserDisconnectedWFD = 311
    UserConnectedWebSMC = 312
    UserDisconnectedWebSMC = 313
    UserCreated         = 1300
    UserRemoved         = 1301
    UserEdited          = 1302
    UserEnabled         = 1303
    UserDisabled        = 1304
    UserMoved           = 1305
    UserPropertiesModified = 1306
    UserPermissionsModified = 1307

    # User group event types
    UserGroupCreated  = 1800
    UserGroupRemoved  = 1801
    UserGroupEdited   = 1802
    UserGroupEnabled  = 1803
    UserGroupDisabled = 1804
    UserGroupRenamed  = 1805
    UserGroupMoved    = 1806
    UserGroupPropertiesModified = 1807
    UserGroupPermissionsModified = 1808

    # Folder event types
    FolderCreated = 1600
    FolderRemoved = 1601
    FolderRenamed = 1602
    FolderMoved   = 1603
    FolderPropertiesModified = 1604
    FolderPermissionsModified = 1605
    FolderExported = 1606
    FolderImported = 1607

    # Server event types
    LicenseAdded             = 400
    LicenseRemoved           = 401
    ServerPropertiesModified = 1500
    ServerPermissionsModifed = 1501
    ApiPermissionsModified   = 1502

    # Miscellaneous
    ConnectionOpened               = 100
    ConnectionClosed               = 101
    SkybotConnected                = 314
    SkybotDisconnected             = 315
    AMExecuteConnected             = 316
    AMExecuteDisconnected          = 317
    InterMapperConnected           = 318
    InterMapperDisconnected        = 319
    ScheduleEnterpriseConnected    = 320
    ScheduleEnterpriseDisconnected = 321
}

# BPA creates some system level objects that have a static ID defined (not stored in the DB).
# These should remain the same across installations on different servers.
class BPASystemAgent {
    static [string] $Condition = "{2C046FDD-97A9-4a79-B34F-0C7A97E9CE69}"
    static [string] $Default   = "{CC3AD52F-C1DC-4d24-B6BE-32467159C86C}"
    static [string] $Previous  = "{AC557F76-ABFF-4860-9ED4-259CC8758C76}"
    static [string] $Triggered = "{C1E0C335-CF54-42f0-AA90-BB2854E37E8A}"
    static [string] $Variable  = "{EEF25965-316C-4a47-98F7-8D113F76333D}"
    [string]GetByID($ID) {
        $result = $null
        switch ($ID) {
            "{2C046FDD-97A9-4a79-B34F-0C7A97E9CE69}" { $result = "Condition" }
            "{CC3AD52F-C1DC-4d24-B6BE-32467159C86C}" { $result = "Default" }
            "{AC557F76-ABFF-4860-9ED4-259CC8758C76}" { $result = "Previous" }
            "{C1E0C335-CF54-42f0-AA90-BB2854E37E8A}" { $result = "Triggered" }
            "{EEF25965-316C-4a47-98F7-8D113F76333D}" { $result = "Variable" }
        }
        return $result
    }
}

class BPATypeDictionary {
    static [PSCustomObject]$AgentGroup   = [PSCustomObject]@{ RestResource = "agent_groups"; RootFolderPath = "\" ; RootFolderName = "AGENTGROUPS"  ; RootFolderID = "{65B26C46-C286-45d8-88AE-2E16774F0DAB}" }
    static [PSCustomObject]$Agent        = [PSCustomObject]@{ RestResource = "agents"      ; RootFolderPath = "\" ; RootFolderName = "TASKAGENTS"   ; RootFolderID = "{A5B6AF52-5DAC-45a0-8B26-602E3E3BBC59}" }  # Only used for agent creation to look up the rest resource
    static [PSCustomObject]$Condition    = [PSCustomObject]@{ RestResource = "conditions"  ; RootFolderPath = "\" ; RootFolderName = "CONDITIONS"   ; RootFolderID = "{5B00CA35-3EFB-41ea-95C0-D8B50B9BFA9F}" }
    static [PSCustomObject]$Process      = [PSCustomObject]@{ RestResource = "processes"   ; RootFolderPath = "\" ; RootFolderName = "PROCESSES"    ; RootFolderID = "{8E19BEB0-9625-4810-AF6E-5EAD7069E83C}" }
    static [PSCustomObject]$ProcessAgent = [PSCustomObject]@{ RestResource = "agents"      ; RootFolderPath = "\" ; RootFolderName = "PROCESSAGENTS"; RootFolderID = "{84334DCF-3643-4988-83CA-79019097AA7D}" }
    static [PSCustomObject]$Task         = [PSCustomObject]@{ RestResource = "tasks"       ; RootFolderPath = "\" ; RootFolderName = "TASKS"        ; RootFolderID = "{E893A7FD-2758-4315-9181-93F8728332E5}" }
    static [PSCustomObject]$TaskAgent    = [PSCustomObject]@{ RestResource = "agents"      ; RootFolderPath = "\" ; RootFolderName = "TASKAGENTS"   ; RootFolderID = "{A5B6AF52-5DAC-45a0-8B26-602E3E3BBC59}" }
    static [PSCustomObject]$User         = [PSCustomObject]@{ RestResource = "users"       ; RootFolderPath = "\" ; RootFolderName = "USERS"        ; RootFolderID = "{CF0A8EFD-08A7-47b1-9A2A-335B743D284A}" }
    static [PSCustomObject]$UserGroup    = [PSCustomObject]@{ RestResource = "user_groups" ; RootFolderPath = "\" ; RootFolderName = "USERGROUPS"   ; RootFolderID = "{E6B6C664-3B87-43a1-AD19-4B60191B8F3C}" }
    static [PSCustomObject]$Workflow     = [PSCustomObject]@{ RestResource = "workflows"   ; RootFolderPath = "\" ; RootFolderName = "WORKFLOWS"    ; RootFolderID = "{589D12C2-1282-4466-B7E3-FE547509AF31}" }
    static [PSCustomObject]$Folder       = [PSCustomObject]@{ RestResource = "folders"     ; RootFolderPath = ""  ; RootFolderName = ""             ; RootFolderID = ""                                       }
}