Automation.psm1




<#
.SYNOPSIS
    Retrieves one or more automation tasks
.DESCRIPTION
    Get-HidAutomationTask will return one or more automation tasks
.PARAMETER AutomationTaskGuid
    The identifier of the task to get, can be specified as an array of strings to retrieve multiple tasks
.PARAMETER Container
    Optional parameter to get only tasks within a certain automation container
    (PowerShell = 1, SelfService = 2, Events = 4, DelegatedForms = 8)
.PARAMETER CompanyName
    The companyname that's used in the helloId URL to know which HelloID tenant to talk to. Required if not connected with Connect-HelloId.
.PARAMETER ApiKey
    The Apikey to use for the api call. Required if not connected with Connect-HelloId.
.PARAMETER ApiSecret
    The Apisecret belonging to the apikey, has to be a securestring. Required if not connected with Connect-HelloId.
.EXAMPLE
    Get-HidAutomationTask -CompanyName "MyCompany" -ApiKey "myapikey" -ApiSecret (ConvertTo-SecureString -AsPlainText -String "password" -Force)
    Returns all automation tasks in the tenant
.EXAMPLE
    Get-HidAutomationTask -automationTaskGuid "f7bfa81a-acf6-4353-8ef6-503bab9a107c"
    Returns the automation task with the guid "f7bfa81a-acf6-4353-8ef6-503bab9a107c"
.EXAMPLE
    Get-HidAutomationTask -Container 8
    Returns all automation tasks within the delegatedforms container
.INPUTS
    You can pipe a string that contains the guid to Get-HidAutomationTask
.OUTPUTS
    Get-HidAutomationTask returns an object for each variable that it gets.
#>

function Get-HidAutomationTask {
    [CmdletBinding(DefaultParameterSetName = 'guid',PositionalBinding = $false)]
    [Alias()]
    [OutputType([String])]
    Param (
        # the GUID of an existing automationtask
        [Parameter(Mandatory = $false,
            ValueFromPipelineByPropertyName = $true,
            ParameterSetName = "Guid")]
        [alias("Guid")]
        [ValidateNotNullOrEmpty()]
        [ValidatePattern("^(\{){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}$")] #Matches a GUID
        [string[]]$AutomationTaskGuid,
                
        <# the name of an existing variable
        [Parameter(Mandatory = $false,
        ValueFromPipeline = $true,
        ValueFromPipelineByPropertyName = $true,
        ParameterSetName = "Name")]
        [ValidateNotNullOrEmpty()]
        [string[]]$Name,
        #>


        # the GUID of an existing variable
        [Parameter(Mandatory = $false,
            ValueFromPipelineByPropertyName = $false,
            ParameterSetName = "container")]
        [ValidateNotNullOrEmpty()]
        [alias("automationContainer")]
        [ValidateSet(1,2,4,8)] #Matches a container
        [int]$Container,

        # Company name used in the URL
        [Parameter(Mandatory= $false)]
        [ValidateNotNullOrEmpty()]
        [string]$CompanyName,
        
        # Api key
        [Parameter(Mandatory= $false)]
        [ValidateNotNullOrEmpty()]
        [string]$ApiKey,

        # Api secret
        [Parameter(Mandatory= $false)]
        [ValidateNotNullOrEmpty()]
        [securestring]$ApiSecret,

        # For preview tenants
        [Parameter(Mandatory = $false)]
        [switch]$IsPreviewTenant
    )
    
    begin {

        if ($PSBoundParameters.ContainsKey("CompanyName") -AND $PSBoundParameters.ContainsKey("ApiKey") -AND $PSBoundParameters.ContainsKey("ApiSecret") ){
            Write-Verbose -Message "Using connectioninfo and credentials from parameter"
            #Create credential object for authentication
            $Cred = New-Object System.Management.Automation.PSCredential ($ApiKey, $ApiSecret)
            if ($IsPreviewTenant){
                $BaseUrl = "https://$CompanyName.preview-helloid.com"
            }
            else {
                $BaseUrl = "https://$CompanyName.helloid.com"
            }
        }
        elseif ($Global:HelloIdConnection.ApiCredentials) {
            Write-Verbose -Message "Using Global connectioninfo and credentials from Connect-HelloId "
            $Cred = $Global:HelloIdConnection.ApiCredentials
            $CompanyName = $Global:HelloIdConnection.CompanyName
            $BaseUrl = $Global:HelloIdConnection.BaseUrl
        }
        else {            
            throw "Error finding connectioninfo. Connect using Connect-HelloId, or specifie CompanyName, ApiKey and ApiSecret"
        }

        #Headers
        $headers = @{
            "Content-Type" = "application/json"
        }
        
    } #End begin
    
    process {        

        if ($PSBoundParameters.ContainsKey("AutomationTaskGuid")){            
            foreach ($guid in $AutomationTaskGuid){
                $URI = "$BaseUrl/api/v1/automationtasks/$guid"
                $output = Invoke-RestMethod -Uri $URI -Method "GET" -Headers $headers -Credential $Cred -UseBasicParsing               
                $output
            }

        }
        elseif ($PSBoundParameters.ContainsKey("Container")) {            
            $URI = "$BaseUrl/api/v1/automationtasks?container=$Container"
            $output = Invoke-RestMethod -Uri $URI -Method "GET" -Headers $headers -Credential $Cred -UseBasicParsing
            $output            
        }
        else {
            $URI = "$BaseUrl/api/v1/automationtasks"
            $output = Invoke-RestMethod -Uri $URI -Method "GET" -Headers $headers -Credential $Cred -UseBasicParsing
            <#
            if ($output.psobject.Properties.name -contains "data"){
                $output = $output.data
            }
            #>

            return $output               
            
        }
        
        
    } #End process
    
    end {
        
    } #End end
} #End function



<#
.SYNOPSIS
    Retrieves a global variable
.DESCRIPTION
    Get-HidGlobalVariable will return one or more global variables
.PARAMETER AutomationVariableGuid
    Specifies the Guid of an existing variable to retrieve, can be specified as an array of strings to retrieve multiple variables
.PARAMETER Name
    Specifies the name of an existing variable to retrieve, can be specified as an array of strings to retrieve multiple variables
.PARAMETER CompanyName
    The companyname that's used in the helloId URL to know which HelloID tenant to talk to. Required if not connected with Connect-HelloId.
.PARAMETER ApiKey
    The Apikey to use for the api call. Required if not connected with Connect-HelloId.
.PARAMETER ApiSecret
    The Apisecret belonging to the apikey, has to be a securestring. Required if not connected with Connect-HelloId.
.EXAMPLE
    Get-HidVariable -CompanyName "MyCompany" -ApiKey "myapikey" -ApiSecret (ConvertTo-SecureString -AsPlainText -String "password" -Force)
    Returns all global variables
.EXAMPLE
    Get-HidVariable -Name "companyName"
    Returns the variable with the name "companyName"
.INPUTS
    You can pipe a string that contains the name or guid to Get-HidVariable
.OUTPUTS
    Get-HidVariable returns an object for each variable that it gets.
#>

function Get-HidGlobalVariable {
    [CmdletBinding(DefaultParameterSetName = 'Name',PositionalBinding = $false)]
    [Alias()]
    [OutputType([String])]
    Param (
        # the GUID of an existing variable
        [Parameter(Mandatory = $false,
            ValueFromPipelineByPropertyName = $true,
            ParameterSetName = "Guid")]
        [alias("Guid")]
        [ValidateNotNullOrEmpty()]
        [ValidatePattern("^(\{){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}$")] #Matches a GUID
        [string[]]$AutomationVariableGuid,
                
        # the name of an existing variable
        [Parameter(Mandatory = $false,
        ValueFromPipeline = $true,
        ValueFromPipelineByPropertyName = $true,
        ParameterSetName = "Name")]
        [ValidateNotNullOrEmpty()]
        [string[]]$Name,

        # Company name used in the URL
        [Parameter(Mandatory= $false)]
        [ValidateNotNullOrEmpty()]
        [string]$CompanyName,
        
        # Api key
        [Parameter(Mandatory= $false)]
        [ValidateNotNullOrEmpty()]
        [string]$ApiKey,

        # Api secret
        [Parameter(Mandatory= $false)]
        [ValidateNotNullOrEmpty()]
        [securestring]$ApiSecret,

        # For preview tenants
        [Parameter(Mandatory = $false)]
        [switch]$IsPreviewTenant
    )
    
    begin {

        if ($PSBoundParameters.ContainsKey("CompanyName") -AND $PSBoundParameters.ContainsKey("ApiKey") -AND $PSBoundParameters.ContainsKey("ApiSecret") ){
            Write-Verbose -Message "Using connectioninfo and credentials from parameter"
            #Create credential object for authentication
            $Cred = New-Object System.Management.Automation.PSCredential ($ApiKey, $ApiSecret)
            if ($IsPreviewTenant){
                $BaseUrl = "https://$CompanyName.preview-helloid.com"
            }
            else {
                $BaseUrl = "https://$CompanyName.helloid.com"
            }
        }
        elseif ($Global:HelloIdConnection.ApiCredentials) {
            Write-Verbose -Message "Using Global connectioninfo and credentials from Connect-HelloId "
            $Cred = $Global:HelloIdConnection.ApiCredentials
            $CompanyName = $Global:HelloIdConnection.CompanyName
            $BaseUrl = $Global:HelloIdConnection.BaseUrl
        }
        else {            
            throw "Error finding connectioninfo. Connect using Connect-HelloId, or specifie CompanyName, ApiKey and ApiSecret"
        }

        #Headers
        $headers = @{
            "Content-Type" = "application/json"
        }
        
    } #End begin
    
    process {        

        if ($PSBoundParameters.ContainsKey("AutomationVariableGuid")){            
            foreach ($guid in $AutomationVariableGuid){
                $URI = "$BaseUrl/api/v1/automation/variables/id/$guid"
                $output = Invoke-RestMethod -Uri $URI -Method "GET" -Headers $headers -Credential $Cred -UseBasicParsing               
                $output
            }

        }
        elseif ($PSBoundParameters.ContainsKey("Name")) {
            foreach ($item in $Name){
                $URI = "$BaseUrl/api/v1/automation/variables/named/$item"
                $output = Invoke-RestMethod -Uri $URI -Method "GET" -Headers $headers -Credential $Cred -UseBasicParsing
                $output
            }
        }
        elseif ($PSBoundParameters.ContainsKey("LinkedItemGuid")){
            foreach ($guid in $LinkedItemGuid){
                $URI = "$BaseUrl/api/v1/automation/variables/$guid"
                $output = Invoke-RestMethod -Uri $URI -Method "GET" -Headers $headers -Credential $Cred -UseBasicParsing               
                $output
            }
        }
        else {
            $URI = "$BaseUrl/api/v1/automation/variables"
            $output = Invoke-RestMethod -Uri $URI -Method "GET" -Headers $headers -Credential $Cred -UseBasicParsing
            <#
            if ($output.psobject.Properties.name -contains "data"){
                $output = $output.data
            }
            #>

            return $output               
            
        }
        
        
    } #End process
    
    end {
        
    } #End end
} #End function



<#
.SYNOPSIS
    Retrieves an automation variable
.DESCRIPTION
    Get-HidVariable will return one or more automation variables
.PARAMETER AutomationVariableGuid
    Specifies the Guid of an existing variable to retrieve, can be specified as an array of strings to retrieve multiple variables
.PARAMETER Name
    Specifies the name of an existing variable to retrieve, can be specified as an array of strings to retrieve multiple variables
.PARAMETER LinkedItemGuid
    When specified gets the automation variables belonging to a specific item.
.PARAMETER CompanyName
    The companyname that's used in the helloId URL to know which HelloID tenant to talk to. Required if not connected with Connect-HelloId.
.PARAMETER ApiKey
    The Apikey to use for the api call. Required if not connected with Connect-HelloId.
.PARAMETER ApiSecret
    The Apisecret belonging to the apikey, has to be a securestring. Required if not connected with Connect-HelloId.
.EXAMPLE
    Get-HidVariable -Name "companyName"
    Returns the variable with the name "companyName"
.EXAMPLE
    Get-HidVariable -LinkedItemGuid "f7bfa81a-acf6-4353-8ef6-503bab9a107c" @parameterSplat
    Returns all variables belonging to the item with guid f7bfa81a-acf6-4353-8ef6-503bab9a107c
.INPUTS
    You can pipe a string that contains the name to Get-HidVariable
.OUTPUTS
    Get-HidVariable returns an object for each variable that it gets.
#>

function Get-HidVariable {
    [CmdletBinding(DefaultParameterSetName = 'Name',PositionalBinding = $false)]
    [Alias()]
    [OutputType([String])]
    Param (
        # the GUID of an existing variable
        [Parameter(Mandatory = $false,
            ValueFromPipelineByPropertyName = $true,
            ParameterSetName = "Guid")]
        [alias("Guid")]
        [ValidateNotNullOrEmpty()]
        [ValidatePattern("^(\{){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}$")] #Matches a GUID
        [string[]]$AutomationVariableGuid,
                
        # the name of an existing variable
        [Parameter(Mandatory = $false,
        ValueFromPipeline = $true,
        ValueFromPipelineByPropertyName = $true,
        ParameterSetName = "Name")]
        [ValidateNotNullOrEmpty()]
        [string[]]$Name,
        
        # the GUID of an existing variable
        [Parameter(Mandatory = $false,
            ValueFromPipelineByPropertyName = $false,
            ParameterSetName = "itemGuid")]
        [alias("ItemGuid")]
        [ValidateNotNullOrEmpty()]
        [ValidatePattern("^(\{){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}$")] #Matches a GUID
        [string[]]$LinkedItemGuid,

        # Company name used in the URL
        [Parameter(Mandatory= $false)]
        [ValidateNotNullOrEmpty()]
        [string]$CompanyName,
        
        # Api key
        [Parameter(Mandatory= $false)]
        [ValidateNotNullOrEmpty()]
        [string]$ApiKey,

        # Api secret
        [Parameter(Mandatory= $false)]
        [ValidateNotNullOrEmpty()]
        [securestring]$ApiSecret,

        # For preview tenants
        [Parameter(Mandatory = $false)]
        [switch]$IsPreviewTenant
    )
    
    begin {

        if ($PSBoundParameters.ContainsKey("CompanyName") -AND $PSBoundParameters.ContainsKey("ApiKey") -AND $PSBoundParameters.ContainsKey("ApiSecret") ){
            Write-Verbose -Message "Using connectioninfo and credentials from parameter"
            #Create credential object for authentication
            $Cred = New-Object System.Management.Automation.PSCredential ($ApiKey, $ApiSecret)
            if ($IsPreviewTenant){
                $BaseUrl = "https://$CompanyName.preview-helloid.com"
            }
            else {
                $BaseUrl = "https://$CompanyName.helloid.com"
            }
        }
        elseif ($Global:HelloIdConnection.ApiCredentials) {
            Write-Verbose -Message "Using Global connectioninfo and credentials from Connect-HelloId "
            $Cred = $Global:HelloIdConnection.ApiCredentials
            $CompanyName = $Global:HelloIdConnection.CompanyName
            $BaseUrl = $Global:HelloIdConnection.BaseUrl
        }
        else {            
            throw "Error finding connectioninfo. Connect using Connect-HelloId, or specifie CompanyName, ApiKey and ApiSecret"
        }

        #Headers
        $headers = @{
            "Content-Type" = "application/json"
        }
        
    } #End begin
    
    process {        

        if ($PSBoundParameters.ContainsKey("AutomationVariableGuid")){            
            foreach ($guid in $AutomationVariableGuid){
                $URI = "$BaseUrl/api/v1/automation/variables/id/$guid"
                $output = Invoke-RestMethod -Uri $URI -Method "GET" -Headers $headers -Credential $Cred -UseBasicParsing               
                $output
            }

        }
        elseif ($PSBoundParameters.ContainsKey("Name")) {
            foreach ($item in $Name){
                $URI = "$BaseUrl/api/v1/automation/variables/named/$item"
                $output = Invoke-RestMethod -Uri $URI -Method "GET" -Headers $headers -Credential $Cred -UseBasicParsing
                $output
            }
        }
        elseif ($PSBoundParameters.ContainsKey("LinkedItemGuid")){
            foreach ($guid in $LinkedItemGuid){
                $URI = "$BaseUrl/api/v1/automation/variables/$guid"
                $output = Invoke-RestMethod -Uri $URI -Method "GET" -Headers $headers -Credential $Cred -UseBasicParsing               
                $output
            }
        }
        else {

            throw "Please specify a name, guid or linkeditemguid"

            <#
            $URI = "$BaseUrl/api/v1/automation/variables"
            $output = Invoke-RestMethod -Uri $URI -Method "GET" -Headers $headers -Credential $Cred -UseBasicParsing
            
            if ($output.psobject.Properties.name -contains "data"){
                $output = $output.data
            }
            #>

            
            #return $output
            
        }
        
        
    } #End process
    
    end {
        
    } #End end
} #End function




<#
.SYNOPSIS
    Creates a new Powershell automation task
.DESCRIPTION
    The New-HidPowershellTask will create a new PowerShell automation task.
.PARAMETER Name
    Name of the powershell task
.PARAMETER ObjectGuid
    Guid of an existing object to link this task to. i.e. a selfservice product or delegated form. If container is 8, and this is set. it will link the task to the delegated form with this GUID for example
.PARAMETER AutomationContainer
    The AutomationContainer of the new powershell task
    (PowerShell = 1, SelfService = 2, Events = 4, DelegatedForms = 8)
.PARAMETER UseTemplate
    Flag indicating where the task will use a PowerShell template or an inline PowerShell script
.PARAMETER PowerShellScriptTemplateGuid
    Identifier of a PowerShell template. Required when useTemplate is set to true
.PARAMETER PowerShellScript
    PowerShell script that will be executed
.PARAMETER AgentPoolGuid
    Agentpool that will be used to execute the PowerShell task
.PARAMETER EmailAddresses
    List of email addresses that are notified when a task finishes
.PARAMETER ScriptTimeout
    Timeout after which the task will be killed when it's still running (when option is set to enabled)
.PARAMETER MetaData
    In the case of a selfservice product, on which state the task will be executed
.PARAMETER IsEnabled
    Is the task enabled
.PARAMETER SendMail
    Should e-mail be sent when task finishes
.PARAMETER IsScriptTimeoutEnabled
    Should task be killed what it hasn't finished after the timeout.
.PARAMETER SendMailWhenFailed
    Should e-mail be sent when task failed
.PARAMETER SendMailForCriticalEvent
    Should e-mail be sent in case of a critical event
.PARAMETER Variables
    Variables that can be used by the PowerShell task
.PARAMETER CompanyName
    The companyname that's used in the helloId URL to know which HelloID tenant to talk to. Required if not connected with Connect-HelloId.
.PARAMETER ApiKey
    The Apikey to use for the api call. Required if not connected with Connect-HelloId.
.PARAMETER ApiSecret
    The Apisecret belonging to the apikey, has to be a securestring. Required if not connected with Connect-HelloId.
.EXAMPLE
    
.EXAMPLE
    
.EXAMPLE
    
.INPUTS
    
.OUTPUTS
    New-HidPowershellTask returns an object representing the task it creates.
#>

function New-HidPowershellTask {
    [CmdletBinding(DefaultParameterSetName = 'guid',PositionalBinding = $false)]
    [Alias()]
    [OutputType([String])]
    Param (
        # Guid of an existing object to link this task to. i.e. a selfservice product or delegated form. if set it links the task to the instance with this GUID, a delegatedform GUID for example
        [Parameter(Mandatory = $false,
            ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNullOrEmpty()]
        [guid]$ObjectGuid,
        
        # the name of the new task, or the new name when a task is being updated
        [Parameter(Mandatory = $true,
        ValueFromPipeline = $true,
        ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNullOrEmpty()]
        [string]$Name,
        

        # the AutomationContainer of the new powershell task
        # (PowerShell = 1, SelfService = 2, Events = 4, DelegatedForms = 8)
        [Parameter(Mandatory = $true,
            ValueFromPipelineByPropertyName = $false)]
        [ValidateNotNullOrEmpty()]
        [ValidateSet(1,2,4,8)] #Matches a container
        [int]$AutomationContainer,

        [Parameter(Mandatory = $false,
            ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNullOrEmpty()]
        [bool]$UseTemplate = $false,

        [Parameter(Mandatory = $false,
            ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNullOrEmpty()]
        [guid]$PowerShellScriptTemplateGuid,

        [Parameter(Mandatory = $false,
            ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNullOrEmpty()]
        [string]$PowerShellScript,

        [Parameter(Mandatory = $false,
            ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNullOrEmpty()]
        [string]$AgentPoolGuid,

        [Parameter(Mandatory = $false,
            ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNullOrEmpty()]
        [string]$EmailAddresses,

        [Parameter(Mandatory = $false,
            ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNullOrEmpty()]
        [int]$ScriptTimeout = 10,

        [Parameter(Mandatory = $false,
            ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNullOrEmpty()]
        [string]$MetaData,

        [Parameter(Mandatory = $false,
            ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNullOrEmpty()]
        [bool]$IsEnabled = $true,

        [Parameter(Mandatory = $false,
            ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNullOrEmpty()]
        [bool]$SendMail = $false,

        [Parameter(Mandatory = $false,
            ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNullOrEmpty()]
        [bool]$IsScriptTimeoutEnabled = $false,

        [Parameter(Mandatory = $false,
            ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNullOrEmpty()]
        [bool]$SendMailWhenFailed = $false,

        [Parameter(Mandatory = $false,
            ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNullOrEmpty()]
        [bool]$SendMailForCriticalEvent = $false,

        [Parameter(Mandatory = $false,
            ValueFromPipelineByPropertyName = $true)]
        [array]$Variables,

        # Company name used in the URL
        [Parameter(Mandatory= $false)]
        [ValidateNotNullOrEmpty()]
        [string]$CompanyName,
        
        # Api key
        [Parameter(Mandatory= $false)]
        [ValidateNotNullOrEmpty()]
        [string]$ApiKey,

        # Api secret
        [Parameter(Mandatory= $false)]
        [ValidateNotNullOrEmpty()]
        [securestring]$ApiSecret,

        # For preview tenants
        [Parameter(Mandatory = $false)]
        [switch]$IsPreviewTenant
    )
    
    begin {
        if ($PSBoundParameters.ContainsKey("CompanyName") -AND $PSBoundParameters.ContainsKey("ApiKey") -AND $PSBoundParameters.ContainsKey("ApiSecret") ){
            Write-Verbose -Message "Using connectioninfo and credentials from parameter"
            #Create credential object for authentication
            $Cred = New-Object System.Management.Automation.PSCredential ($ApiKey, $ApiSecret)
            if ($IsPreviewTenant){
                $BaseUrl = "https://$CompanyName.preview-helloid.com"
            }
            else {
                $BaseUrl = "https://$CompanyName.helloid.com"
            }
        }
        elseif ($Global:HelloIdConnection.ApiCredentials) {
            Write-Verbose -Message "Using Global connectioninfo and credentials from Connect-HelloId "
            $Cred = $Global:HelloIdConnection.ApiCredentials
            $CompanyName = $Global:HelloIdConnection.CompanyName
            $BaseUrl = $Global:HelloIdConnection.BaseUrl
        }
        else {            
            throw "Error finding connectioninfo. Connect using Connect-HelloId, or specifie CompanyName, ApiKey and ApiSecret"
        }

        $JsonVariables = ConvertTo-Json -InputObject $Variables -Depth 15
        
        #Headers
        $headers = @{
            "Content-Type" = "application/json"
        }
        
    } #End begin
    
    process {        

        $SbBody = [System.Text.StringBuilder]::new()
        $null = $SbBody.AppendLine("{") 
        $null = $SbBody.AppendLine("`"name`": `"$Name`",")
        #if ($PSBoundParameters.ContainsKey("ObjectGuid")) {$null = $SbBody.AppendLine("`"automationTaskGuid`": `"$AutomationTaskGuid`",")}
        $null = $SbBody.AppendLine("`"automationContainer`": $AutomationContainer,")
        if ($PSBoundParameters.ContainsKey("ObjectGuid")){ $null = $SbBody.AppendLine("`"objectGuid`": `"$ObjectGuid`",") }
        else { $null = $SbBody.AppendLine("`"objectGuid`": null,") }
        if ($PSBoundParameters.ContainsKey("AgentPoolGuid")) { $null = $SbBody.AppendLine("`"agentPoolGuid`": `"$AgentPoolGuid`",") }
        else { $null = $SbBody.AppendLine("`"agentPoolGuid`": null,") }
        $null = $SbBody.AppendLine("`"emailAddresses`": `"$EmailAddresses`",")
        $null = $SbBody.AppendLine("`"scriptTimeout`": $ScriptTimeout,")
        $null = $SbBody.AppendLine("`"uSN`": 1,")
        if ($PSBoundParameters.ContainsKey("MetaData")) { $null = $SbBody.AppendLine("`"metaData`": `"$MetaData`",") }
        else {$null = $SbBody.AppendLine("`"metaData`": null,")}
        $null = $SbBody.AppendLine("`"isEnabled`": $(($IsEnabled).ToString().ToLower()),")
        $null = $SbBody.AppendLine("`"sendMail`": $(($SendMailForCriticalEvent).ToString().ToLower()),")
        $null = $SbBody.AppendLine("`"isScriptTimeoutEnabled`": $(($IsScriptTimeoutEnabled).ToString().ToLower()),")
        $null = $SbBody.AppendLine("`"sendMailWhenFailed`": $(($SendMailWhenFailed).ToString().ToLower()),")
        $null = $SbBody.AppendLine("`"sendMailForCriticalEvent`": $(($SendMailForCriticalEvent).ToString().ToLower()),")
        $null =  $SbBody.AppendLine("`"useTemplate`": $(($UseTemplate).ToString().ToLower()),")
        if ($PSBoundParameters.ContainsKey("PowerShellScriptTemplateGuid")) { $null = $SbBody.AppendLine("`"powerShellScriptTemplateGuid`": `"$PowerShellScriptTemplateGuid`",") }
        else {$null = $SbBody.AppendLine("`"powerShellScriptTemplateGuid`": null,")}       
        if ($PSBoundParameters.ContainsKey("PowerShellScript")) { $null = $SbBody.AppendLine("`"powerShellScript`": `"$PowerShellScript`",") }
        else { $null = $SbBody.AppendLine("`"powerShellScript`": null,") }
        $null = $SbBody.AppendLine("`"variables`": $JsonVariables")
        $null = $SbBody.AppendLine("}")

        Write-Debug -Message "Body is: `n$($SbBody.ToString())"

        $URI = "$BaseUrl/api/v1/automationtasks/powershell"
        $output = Invoke-RestMethod -Uri $URI -Method "POST" -Body ($SbBody.ToString()) -Headers $headers -Credential $Cred -UseBasicParsing
        <#
        if ($output.psobject.Properties.name -contains "data"){
            $output = $output.data
        }
        #>

        return $output               
            
        
        
        
    } #End process
    
    end {
        
    } #End end
} #End function






<#
.SYNOPSIS
    Updates a Powershell automation task
.DESCRIPTION
    The New-HidPowershellTask will create a new PowerShell automation task.
.PARAMETER AutomationTaskGuid
    Guid of an existing task in order to update it.
.PARAMETER Name
    New name of the powershell task
.PARAMETER ObjectGuid
    Guid of an existing object to link this task to. i.e. a selfservice product or delegated form. If container is 8, and this is set. it will link the task to the delegated form with this GUID for example
.PARAMETER AutomationContainer
    The AutomationContainer of the new powershell task
    (PowerShell = 1, SelfService = 2, Events = 4, DelegatedForms = 8)
.PARAMETER UseTemplate
    Flag indicating where the task will use a PowerShell template or an inline PowerShell script
.PARAMETER PowerShellScriptTemplateGuid
    Identifier of a PowerShell template. Required when useTemplate is set to true
.PARAMETER PowerShellScript
    PowerShell script that will be executed
.PARAMETER AgentPoolGuid
    Agentpool that will be used to execute the PowerShell task
.PARAMETER EmailAddresses
    List of email addresses that are notified when a task finishes
.PARAMETER ScriptTimeout
    Timeout after which the task will be killed when it's still running (when option is set to enabled)
.PARAMETER MetaData
    In the case of a selfservice product, on which state the task will be executed
.PARAMETER IsEnabled
    Is the task enabled
.PARAMETER SendMail
    Should e-mail be sent when task finishes
.PARAMETER IsScriptTimeoutEnabled
    Should task be killed what it hasn't finished after the timeout.
.PARAMETER SendMailWhenFailed
    Should e-mail be sent when task failed
.PARAMETER SendMailForCriticalEvent
    Should e-mail be sent in case of a critical event
.PARAMETER Variables
    Variables that can be used by the PowerShell task
.PARAMETER CompanyName
    The companyname that's used in the helloId URL to know which HelloID tenant to talk to. Required if not connected with Connect-HelloId.
.PARAMETER ApiKey
    The Apikey to use for the api call. Required if not connected with Connect-HelloId.
.PARAMETER ApiSecret
    The Apisecret belonging to the apikey, has to be a securestring. Required if not connected with Connect-HelloId.
.EXAMPLE
    
.EXAMPLE
    
.EXAMPLE
    
.INPUTS
    
.OUTPUTS
#>

function Update-HidPowershellTask {
    [CmdletBinding(DefaultParameterSetName = 'guid',PositionalBinding = $false)]
    [Alias("Set-HidPowershellTask")]
    [OutputType([String])]
    Param (
        
        #Guid of an existing task in order to update it.
        [Parameter(Mandatory = $true,
        ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNullOrEmpty()]
        [guid]$AutomationTaskGuid,

        # the name of the new task, or the new name when a task is being updated
        [Parameter(Mandatory = $false,
        ValueFromPipeline = $true,
        ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNullOrEmpty()]
        [string]$Name,

        # Guid of an existing object to link this task to. i.e. a selfservice product or delegated form. if set it links the task to the instance with this GUID, a delegatedform GUID for example
        [Parameter(Mandatory = $false,
            ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNullOrEmpty()]
        [guid]$ObjectGuid,        

        # the AutomationContainer of the new powershell task
        # (PowerShell = 1, SelfService = 2, Events = 4, DelegatedForms = 8)
        [Parameter(Mandatory = $false,
            ValueFromPipelineByPropertyName = $false)]
        [ValidateNotNullOrEmpty()]
        [ValidateSet(1,2,4,8)] #Matches a container
        [int]$AutomationContainer,

        [Parameter(Mandatory = $false,
            ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNullOrEmpty()]
        [bool]$UseTemplate = $false,

        [Parameter(Mandatory = $false,
            ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNullOrEmpty()]
        [guid]$PowerShellScriptTemplateGuid,

        [Parameter(Mandatory = $false,
            ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNullOrEmpty()]
        [string]$PowerShellScript,

        [Parameter(Mandatory = $false,
            ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNullOrEmpty()]
        [string]$AgentPoolGuid,

        [Parameter(Mandatory = $false,
            ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNullOrEmpty()]
        [string]$EmailAddresses,

        [Parameter(Mandatory = $false,
            ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNullOrEmpty()]
        [int]$ScriptTimeout = 10,

        [Parameter(Mandatory = $false,
            ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNullOrEmpty()]
        [string]$MetaData,

        [Parameter(Mandatory = $false,
            ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNullOrEmpty()]
        [bool]$IsEnabled = $true,

        [Parameter(Mandatory = $false,
            ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNullOrEmpty()]
        [bool]$SendMail = $false,

        [Parameter(Mandatory = $false,
            ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNullOrEmpty()]
        [bool]$IsScriptTimeoutEnabled = $false,

        [Parameter(Mandatory = $false,
            ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNullOrEmpty()]
        [bool]$SendMailWhenFailed = $false,

        [Parameter(Mandatory = $false,
            ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNullOrEmpty()]
        [bool]$SendMailForCriticalEvent = $false,

        [Parameter(Mandatory = $false,
            ValueFromPipelineByPropertyName = $true)]
        [array]$Variables,

        # Company name used in the URL
        [Parameter(Mandatory= $false)]
        [ValidateNotNullOrEmpty()]
        [string]$CompanyName,
        
        # Api key
        [Parameter(Mandatory= $false)]
        [ValidateNotNullOrEmpty()]
        [string]$ApiKey,

        # Api secret
        [Parameter(Mandatory= $false)]
        [ValidateNotNullOrEmpty()]
        [securestring]$ApiSecret,

        # For preview tenants
        [Parameter(Mandatory = $false)]
        [switch]$IsPreviewTenant
    )
    
    begin {
        if ($PSBoundParameters.ContainsKey("CompanyName") -AND $PSBoundParameters.ContainsKey("ApiKey") -AND $PSBoundParameters.ContainsKey("ApiSecret") ){
            Write-Verbose -Message "Using connectioninfo and credentials from parameter"
            #Create credential object for authentication
            $Cred = New-Object System.Management.Automation.PSCredential ($ApiKey, $ApiSecret)
            if ($IsPreviewTenant){
                $BaseUrl = "https://$CompanyName.preview-helloid.com"
            }
            else {
                $BaseUrl = "https://$CompanyName.helloid.com"
            }
        }
        elseif ($Global:HelloIdConnection.ApiCredentials) {
            Write-Verbose -Message "Using Global connectioninfo and credentials from Connect-HelloId "
            $Cred = $Global:HelloIdConnection.ApiCredentials
            $CompanyName = $Global:HelloIdConnection.CompanyName
            $BaseUrl = $Global:HelloIdConnection.BaseUrl
        }
        else {            
            throw "Error finding connectioninfo. Connect using Connect-HelloId, or specifie CompanyName, ApiKey and ApiSecret"
        }

        $JsonVariables = ConvertTo-Json -InputObject $Variables -Depth 15
        
        #Headers
        $headers = @{
            "Content-Type" = "application/json"
        }
        
    } #End begin
    
    process {        

        $SbBody = [System.Text.StringBuilder]::new()
        $null = $SbBody.AppendLine("{") 
        if ($PSBoundParameters.ContainsKey("Name")) {$null = $SbBody.AppendLine("`"name`": `"$Name`",") }
        if ($PSBoundParameters.ContainsKey("AutomationContainer")) {$null = $SbBody.AppendLine("`"automationContainer`": $AutomationContainer,")}
        if ($PSBoundParameters.ContainsKey("ObjectGuid")){ $null = $SbBody.AppendLine("`"objectGuid`": `"$ObjectGuid`",") }
        if ($PSBoundParameters.ContainsKey("AgentPoolGuid")) { $null = $SbBody.AppendLine("`"agentPoolGuid`": `"$AgentPoolGuid`",") }
        if ($PSBoundParameters.ContainsKey("EmailAddresses")) { $null = $SbBody.AppendLine("`"emailAddresses`": `"$EmailAddresses`",") }
        if ($PSBoundParameters.ContainsKey("ScriptTimeout")) { $null = $SbBody.AppendLine("`"scriptTimeout`": $ScriptTimeout,") }
        if ($PSBoundParameters.ContainsKey("MetaData")) { $null = $SbBody.AppendLine("`"metaData`": `"$MetaData`",") }
        if ($PSBoundParameters.ContainsKey("IsEnabled")) { $null = $SbBody.AppendLine("`"isEnabled`": $(($IsEnabled).ToString().ToLower()),") }
        if ($PSBoundParameters.ContainsKey("SendMailForCriticalEvent")) { $null = $SbBody.AppendLine("`"sendMail`": $(($SendMailForCriticalEvent).ToString().ToLower()),") }
        if ($PSBoundParameters.ContainsKey("IsScriptTimeoutEnabled")) { $null = $SbBody.AppendLine("`"isScriptTimeoutEnabled`": $(($IsScriptTimeoutEnabled).ToString().ToLower()),") }
        if ($PSBoundParameters.ContainsKey("SendMailWhenFailed")) { $null = $SbBody.AppendLine("`"sendMailWhenFailed`": $(($SendMailWhenFailed).ToString().ToLower()),") }
        if ($PSBoundParameters.ContainsKey("SendMailForCriticalEvent")) { $null = $SbBody.AppendLine("`"sendMailForCriticalEvent`": $(($SendMailForCriticalEvent).ToString().ToLower()),") }
        if ($PSBoundParameters.ContainsKey("UseTemplate")) { $null =  $SbBody.AppendLine("`"useTemplate`": $(($UseTemplate).ToString().ToLower()),") }
        if ($PSBoundParameters.ContainsKey("PowerShellScriptTemplateGuid")) { $null = $SbBody.AppendLine("`"powerShellScriptTemplateGuid`": `"$PowerShellScriptTemplateGuid`",") }
        if ($PSBoundParameters.ContainsKey("PowerShellScript")) { $null = $SbBody.AppendLine("`"powerShellScript`": `"$PowerShellScript`",") }
        if ($PSBoundParameters.ContainsKey("Variables")) { $null = $SbBody.AppendLine("`"variables`": $JsonVariables,") }
        $null = $SbBody.AppendLine("`"automationTaskGuid`": `"$AutomationTaskGuid`"")
        $null = $SbBody.AppendLine("}")

        Write-Debug -Message "Body is: `n$($SbBody.ToString())"

        $URI = "$BaseUrl/api/v1/automationtasks/powershell"
        $output = Invoke-RestMethod -Uri $URI -Method "POST" -Body ($SbBody.ToString()) -Headers $headers -Credential $Cred -UseBasicParsing
        <#
        if ($output.psobject.Properties.name -contains "data"){
            $output = $output.data
        }
        #>

        return $output 
        
    } #End process
    
    end {
        
    } #End end
} #End function








<#
.SYNOPSIS
    Removes a powershell task
.DESCRIPTION
    Removes a powershell task based on the guid
.PARAMETER AutomationTaskGuid
    The GUID of the powershell task that you want to delete.
.PARAMETER CompanyName
    The companyname that's used in the helloId URL to know which HelloID tenant to talk to. Required if not connected with Connect-HelloId.
.PARAMETER ApiKey
    The Apikey to use for the api call. Required if not connected with Connect-HelloId.
.PARAMETER ApiSecret
    The Apisecret belonging to the apikey, has to be a securestring. Required if not connected with Connect-HelloId.
.EXAMPLE
    Remove-HidDelegatedFormCategory -DelegatedFormCategoryGuid "c31fd53a-b346-4bb4-9a67-f9406d3968db"

    Removes the category with the specified GUID
.INPUTS
    Inputs to this cmdlet (if any)
.OUTPUTS
    Output from this cmdlet (if any)
#>

function Remove-HidPowershellTask {
    [CmdletBinding(DefaultParameterSetName = 'Parameter Set 1',
        PositionalBinding = $false)]
    [Alias()]
    [OutputType([String])]
    Param (
        # The GUID of the powershell task that you want to delete.
        [Parameter(Mandatory = $true,
            ValueFromPipeline = $true,
            ValueFromPipelineByPropertyName = $true)]
        [alias("Guid")]
        [ValidateNotNullOrEmpty()]
        [guid[]]$AutomationTaskGuid,        
        
        # Company name used in the URL
        [Parameter(Mandatory= $false)]
        [ValidateNotNullOrEmpty()]
        [string]$CompanyName,
        
        # Api key
        [Parameter(Mandatory= $false)]
        [ValidateNotNullOrEmpty()]
        [string]$ApiKey,

        # Api secret
        [Parameter(Mandatory= $false)]
        [ValidateNotNullOrEmpty()]
        [securestring]$ApiSecret,

        # For preview tenants
        [Parameter(Mandatory = $false)]
        [switch]$IsPreviewTenant
    )
    
    begin {
        if ($PSBoundParameters.ContainsKey("CompanyName") -AND $PSBoundParameters.ContainsKey("ApiKey") -AND $PSBoundParameters.ContainsKey("ApiSecret") ){
            Write-Verbose -Message "Using connectioninfo and credentials from parameter"
            #Create credential object for authentication
            $Cred = New-Object System.Management.Automation.PSCredential ($ApiKey, $ApiSecret)
            if ($IsPreviewTenant){
                $BaseUrl = "https://$CompanyName.preview-helloid.com"
            }
            else {
                $BaseUrl = "https://$CompanyName.helloid.com"
            }
        }
        elseif ($Global:HelloIdConnection.ApiCredentials) {
            Write-Verbose -Message "Using Global connectioninfo and credentials from Connect-HelloId "
            $Cred = $Global:HelloIdConnection.ApiCredentials
            $CompanyName = $Global:HelloIdConnection.CompanyName
            $BaseUrl = $Global:HelloIdConnection.BaseUrl
        }
        else {            
            throw "Error finding connectioninfo. Connect using Connect-HelloId, or specify CompanyName, ApiKey and ApiSecret"
        }

        #Headers
        $headers = @{
            "Content-Type" = "application/json"
        }
        
        
    } #End begin
    
    process {        

        foreach ($guid in $AutomationTaskGuid){
        #Uri
        $URI = "$BaseUrl/api/v1/automationtasks/powershell/$guid"        
        Invoke-RestMethod -Uri $URI -Method "DELETE" -Headers $headers -Credential $Cred -UseBasicParsing        
        } #end foreach

    } #End process
    
    end {
    } #End end
} #End function







<#
.SYNOPSIS
    Creates or updates a global variable
.DESCRIPTION
    The Create global automation variable operation will create a new variable or update an existing variable with the specified request body
.PARAMETER Name
    The name of the global variable to create or update
.PARAMETER Value
    Value of the variable
.PARAMETER Secret
    If its a secret parameter, a password for example
.PARAMETER Overwrite
    A boolean value indicating if the variable should be overwritten it already exists (based on the variable name), default is True
.PARAMETER CompanyName
    The companyname that's used in the helloId URL to know which HelloID tenant to talk to. Required if not connected with Connect-HelloId.
.PARAMETER ApiKey
    The Apikey to use for the api call. Required if not connected with Connect-HelloId.
.PARAMETER ApiSecret
    The Apisecret belonging to the apikey, has to be a securestring. Required if not connected with Connect-HelloId.
.EXAMPLE

.EXAMPLE

.INPUTS
    Inputs to this cmdlet (if any)
.OUTPUTS
    Output from this cmdlet (if any)
#>

function Set-HidGlobalVariable {
    [CmdletBinding(DefaultParameterSetName = 'Parameter Set 1',
        PositionalBinding = $false)]
    [Alias()]
    [OutputType([String])]
    Param (
        # name of the global variable
        [Parameter(Mandatory= $true,
            ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNullOrEmpty()]
        [string]$Name,

        # value of the variable
        [Parameter(Mandatory= $true,
            ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNullOrEmpty()]
        [string]$Value,
        
        # secret yes/no
        [Parameter(Mandatory= $false,
            ValueFromPipelineByPropertyName = $false)]
        [ValidateNotNullOrEmpty()]
        [bool]$Secret = $false,
        
        # overwrite if exists
        [Parameter(Mandatory= $false,
            ValueFromPipelineByPropertyName = $false)]
        [ValidateNotNullOrEmpty()]
        [bool]$Overwrite = $false,

        # Company name used in the URL
        [Parameter(Mandatory= $false)]
        [ValidateNotNullOrEmpty()]
        [string]$CompanyName,
        
        # Api key
        [Parameter(Mandatory= $false)]
        [ValidateNotNullOrEmpty()]
        [string]$ApiKey,

        # Api secret
        [Parameter(Mandatory= $false)]
        [ValidateNotNullOrEmpty()]
        [securestring]$ApiSecret,

        # For preview tenants
        [Parameter(Mandatory = $false)]
        [switch]$IsPreviewTenant
    )
    
    begin {
        if ($PSBoundParameters.ContainsKey("CompanyName") -AND $PSBoundParameters.ContainsKey("ApiKey") -AND $PSBoundParameters.ContainsKey("ApiSecret") ){
            Write-Verbose -Message "Using connectioninfo and credentials from parameter"
            #Create credential object for authentication
            $Cred = New-Object System.Management.Automation.PSCredential ($ApiKey, $ApiSecret)
            if ($IsPreviewTenant){
                $BaseUrl = "https://$CompanyName.preview-helloid.com"
            }
            else {
                $BaseUrl = "https://$CompanyName.helloid.com"
            }
        }
        elseif ($Global:HelloIdConnection.ApiCredentials) {
            Write-Verbose -Message "Using Global connectioninfo and credentials from Connect-HelloId "
            $Cred = $Global:HelloIdConnection.ApiCredentials
            $CompanyName = $Global:HelloIdConnection.CompanyName
            $BaseUrl = $Global:HelloIdConnection.BaseUrl
        }
        else {            
            throw "Error finding connectioninfo. Connect using Connect-HelloId, or specifie CompanyName, ApiKey and ApiSecret"
        }

        

        #Headers
        $headers = @{
            "Content-Type" = "application/json"
        }

        #Uri
        $URI = "$BaseUrl/api/v1/automation/variable/"
    } #End begin
    
    process {
        
        
        $SbBody = [System.Text.StringBuilder]::new()
        $null = $SbBody.AppendLine("{")
        $null = $SbBody.AppendLine("`"name`": `"$Name`",")
        $null = $SbBody.AppendLine("`"value`": `"$Value`",")
        $null = $SbBody.AppendLine("`"secret`": $(($Secret).ToString().ToLower()),")
        $null = $SbBody.AppendLine("`"overwriteIfExists`": $(($Overwrite).ToString().ToLower())")
        $null = $SbBody.AppendLine("}")
        

        Write-Debug -Message "Body is: `n$($sbBody.ToString())"
        $output = Invoke-RestMethod -Uri $URI -Method "POST" -Headers $headers -Body ($sbBody.ToString()) -Credential $Cred -UseBasicParsing


    } #End process
    
    end {
        return $output
    } #End end
} #End function