SentinelOne.Tools.psm1

function Get-S1Command {
  [CmdletBinding()]
  param (
    [Parameter(Mandatory = $true)]
    [string]
    $Command,

    [Parameter(Mandatory = $false)]
    [string[]]
    $Parameters
  )

  process {
    if ($Parameters) {
      $params = $Parameters -join ''
      return "Import-Module SentinelOne.Tools
$($params.Substring(1)) | $command"

    } else {
      return "Import-Module SentinelOne.Tools
$command"

    }
  }
}

function Get-S1CommandParameter {
  [CmdletBinding()]
  param (
      [Parameter(Mandatory = $true)]
      [pscustomobject]
      $Invocation,

      [Parameter(Mandatory = $true,
      ValueFromPipelineByPropertyName = $true)]
      [String]
      $ApiEndpoint
  )

  Begin {
    $mi = @{BoundParameters = @{}}
  }

  Process {
    $mi.BoundParameters += [System.Collections.Hashtable]::new($Invocation.BoundParameters)
    $ApiEndpoint = $ApiEndpoint -replace '(\?(&+))','?' -replace '&+','&' -replace '&$',''
    Write-Debug $ApiEndpoint
    ($ApiEndpoint.Split("?")[1]).Split("&") | & { process {
      if (!($_.StartsWith('limit='))) {
        $mi.BoundParameters += @{ $_.Split('=')[0] = $_.Split('=')[1] }
      }
    }}

    if ($mi.BoundParameters.Keys -notmatch 'InputObject|SaveCommand') {
      $txt += ",[pscustomobject]@{"
      $txt += $mi.BoundParameters.Keys | & { process {
        if ($_ -match 'Filter') {
          " $_ = '$(($mi.BoundParameters.$_ | ConvertTo-Json) -replace '"",','"";' -replace ':',"" ="" -replace '{','@{' -replace '\s','')';"
        } elseif ($_ -notmatch 'InputObject|SaveCommand') {
          "$_ = '$($mi.BoundParameters.$_)';"
        }
      }}
      $txt += "}"
    }

    $txt -join ''
  }
}

function Get-S1Filter {
  [CmdletBinding(DefaultParameterSetName = 'All')]
  param (
    [Parameter(Mandatory = $true,
      ValueFromPipelineByPropertyName = $true)]
    [string]
    $ApiEndpoint,

    [Parameter(Mandatory = $true,
      ValueFromPipeline = $true,
      ValueFromRemainingArguments = $true)]
    [pscustomobject]
    $InputObject
  )

  Begin {
    # Remove duplicate code
    $filterBy = {
      if (([string]::IsNullOrEmpty($value) -or ([string]::IsNullOrWhiteSpace($value)))) {
        return $ApiEndpoint
      }
      $pattern = "^(.*$key=)([^&]+)(.*)$"
      if ($ApiEndpoint -match $pattern) {
        return ($ApiEndpoint -replace $pattern,('$1 {0} $3' -f $value) -replace ' ', '')
      } else {
        return ("{0}{1}$key={2}" -f $ApiEndpoint, $(if ($ApiEndpoint.IndexOf('?') -ne -1) {"&"} else {"?"}), $value)
      }
    }
  }

  Process {

    switch -regex (($InputObject | Get-Member -MemberType Properties).Name) {
      accountId {
        $key,$value = 'accountIds',$InputObject.$_
        $ApiEndpoint = Invoke-Command -ScriptBlock $filterBy
        continue
      }

      siteId {
        $key,$value = 'siteIds',$InputObject.$_
        $ApiEndpoint = Invoke-Command -ScriptBlock $filterBy
        continue
      }

      groupId {
        $key,$value = 'groupIds',$InputObject.$_
        $ApiEndpoint = Invoke-Command -ScriptBlock $filterBy
        continue
      }

      agentId {
        $key,$value = 'agentIds',$InputObject.$_
        $ApiEndpoint = Invoke-Command -ScriptBlock $filterBy
        continue
      }

      agentId {
        $key,$value = 'agentIds',$InputObject.$_
        $ApiEndpoint = Invoke-Command -ScriptBlock $filterBy
        continue
      }

      # # Unsure what this is used for.. Commenting out to prevent anything breaking
      # collectionId {
      # $key,$value = 'collectionIds',$InputObject.$_
      # $ApiEndpoint = Invoke-Command -ScriptBlock $filterBy
      # continue
      # }

      # Specific - Multiple
      GetByRegistrationToken {
        $key,$value = 'registrationToken',$InputObject.$_
        $ApiEndpoint = Invoke-Command -ScriptBlock $filterBy
        continue
      }

      GetByName {
        $key,$value = 'name',$InputObject.$_
        $ApiEndpoint = Invoke-Command -ScriptBlock $filterBy
        continue
      }

      GetByThreatId {
        $key,$value = 'threatIds',$InputObject.$_
        $ApiEndpoint = Invoke-Command -ScriptBlock $filterBy
        continue
      }

      GetByUserId {
        $key,$value = 'userIds',$InputObject.$_
        $ApiEndpoint = Invoke-Command -ScriptBlock $filterBy
        continue
      }

      # Specific to Get-S1Agent
      GetAgentByComputerName {
        $key,$value = 'computerName',$InputObject.$_
        $ApiEndpoint = Invoke-Command -ScriptBlock $filterBy
        continue
      }

      # Specific to Get-S1Activity
      GetActivityById {
        $key,$value = 'activityIds',$InputObject.$_
        $ApiEndpoint = Invoke-Command -ScriptBlock $filterBy
        continue
      }

      GetActivityByActivityType {
        $key,$value = 'activityTypes',$InputObject.$_
        $ApiEndpoint = Invoke-Command -ScriptBlock $filterBy
        continue
      }

      # Specific to Get-S1Site
      GetSiteByType {
        $key,$value = 'siteType',$InputObject.$_
        $ApiEndpoint = Invoke-Command -ScriptBlock $filterBy
        continue
      }

      GetSiteByState {
        $key,$value = 'state',$InputObject.$_.ToLower()
        $ApiEndpoint = Invoke-Command -ScriptBlock $filterBy
        continue
      }

      # Specific to Get-S1User
      GetByUserEmail {
        $key,$value = 'email',$InputObject.$_
        $ApiEndpoint = Invoke-Command -ScriptBlock $filterBy
        continue
      }
    }
  }

  End {
    Write-Output ($ApiEndpoint -replace '\?\&','?')
    Remove-Variable -Name InputObject
  }
}

# Private Function Example - Replace With Your Function
function Add-PrivateFunction {

  [CmdletBinding()]

  Param (
    # Your parameters go here...
  )

  # Your function code goes here...
  Write-Output "Your private function ran!"

}

function Get-SentinelOneConfig {

  param(
    [Parameter(Mandatory=$false,
      HelpMessage = 'Local app data folder name')]
    [string] $ConfigFolderName,

    [Parameter(Mandatory=$false,
      HelpMessage = 'XML config file name')]
    [string] $ConfigFileName
  )

  Begin {
    Write-Verbose "Retrieving config file"

    if (!$PSBoundParameters.ContainsKey('ConfigFolderName')) {
      $ConfigFolderName = "SentinelOne.Tools"
    }

    if (!$PSBoundParameters.ContainsKey('ConfigFileName')) {
      $ConfigFileName = "SentinelOne.Tools.xml"
    }

    # Define variables
    $configFileFolder = [io.path]::combine($ENV:LOCALAPPDATA, $ConfigFolderName)
    $configFile = [io.path]::combine($configFileFolder, $ConfigFileName)

    Write-Verbose ("Config file location: {0}" -f $configFile)
    # Check if folder / config file exists
    if (!(Test-Path -Path $configFile)) {
      # File does not exist, create it
      Write-Verbose ("Config file does not exist. Running New-SentinelOneConfig")
      Write-Warning ("Creating new config file: {0}" -f $configFile)
      try {
        New-SentinelOneConfig -ConfigFolderName $ConfigFolderName -ConfigFileName $ConfigFileName
      } catch {
        Write-Error "New-SentinelOneConfig failed to complete successfully. Try running it manually."
        exit 1
      }
    }
  }

  Process {

    $config = Import-Clixml -Path $configFile

    Write-Verbose ("Config imported")
    Write-Debug ("Config compiled: {0}" -f $config)
  }

  End {
    Write-Output $config
    $config = $null
    Remove-Variable -Name config
  }
}

function Get-S1Activity {
  <#
  .DESCRIPTION
    Get the activities, and their data, that match the filters. We recommend that you set some values for the filters. The full list will be too large to be useful.
  .SYNOPSIS
    Get the activities, and their data, that match the filters.
  .PARAMETER ManagementUrl
    The base URL for the customer's SentinelOne environment
  .PARAMETER Credential
    PSCredential Object containing the API Key in the Password field
 
  .PARAMETER Filter
    Filters to apply to the query in hashtable format.
    eg.
    $filters = @{
      groupIds = @(225494730938493804, 225494730938493915)
      sortBy = 'id'
    }
    Get-S1Activity -Filter $filters
  .PARAMETER ByActivityID
    ID of the activity
  .PARAMETER ByActivityType
    List of Activity Type IDs to filter results by
  .PARAMETER ByGroupID
    SentinelOne Group ID
  .PARAMETER BySiteID
    SentinelOne Site ID
  .OUTPUTS
    Returns a PSCustomObject containing the Activities and their data
    Returns ErrorObject if an error is encountered
  .EXAMPLE
    Get-S1Activity -ManagementUrl "apne1-1110-mssp.sentinelone.net" -Credential (Get-PSCredential)
 
  #>

  [CmdletBinding(DefaultParameterSetName = 'All')]
  param(
        [Parameter(Mandatory=$false,
      HelpMessage = 'The base URL for the customers SentinelOne environment')]
    [string] $ManagementUrl,

        [Parameter(Mandatory=$false,
      HelpMessage = 'PSCredential Object containing the API Key in the Password field')]
    [PsCredential] $Credential,


        [Parameter(Mandatory=$false,
      HelpMessage = 'Filters to apply to the query in hashtable format.
      eg.
      $filters = @{
        groupIds = @(225494730938493804, 225494730938493915)
        sortBy = "id"
      }
      Get-S1Activity -Filter $filters'
)]
    [hashtable] $Filter,

    [Alias('activityId')]
    [Parameter(Mandatory=$false,
      HelpMessage = 'ID of the activity',
      ValueFromPipelineByPropertyName = $true)]
    [string]$ByActivityID,

    [Alias('activityTypeId')]
    [Parameter(Mandatory=$false,
      HelpMessage = 'List of Activity Type IDs to filter results by',
      ValueFromPipelineByPropertyName = $true)]
    [string]$ByActivityType,

    [Parameter(Mandatory = $false)]
    [switch]
    $SaveCommand,

    [Parameter(Mandatory=$false,
      HelpMessage = 'Pipeline handler',
      ValueFromPipeline = $true,
      ValueFromRemainingArguments = $true,
      DontShow = $true)]
    [pscustomobject]$InputObject
    )

  Begin {
    # Use Max Page Size to reduce the number of requests
    $limit = 1000
    $ApiVersion = '2.1'
    $ApiEndpoint = [System.Text.StringBuilder]'activities'

    $Parameters = @()
    $Parameters += ("limit={0}" -f $limit)

    if ($Filter) {
      # An Agent filter was specified
      $Parameters += $Filter.keys | & { process {
        "$_={0}" -f $(if ($Filter.$_.GetType() -eq [Object[]]) {Join-String -Separator "," -InputObject $Filter.$_} else {$Filter.$_})
      }}
    }

    $ParamString = $Parameters -join '&'

    $null = $ApiEndpoint.Append("?")
    $null = $ApiEndpoint.Append($ParamString)
    $ApiEndpoint = $ApiEndpoint.ToString()

    if ($ManagementUrl) {
      $functionParameters += @{
        ManagementUrl = $ManagementUrl
      }
    }

    if ($Credential) {
      $functionParameters += @{
        Credential = $Credential
      }
    }
  }

  Process {

    if ($ByActivityID) { # Specific
      $ApiEndpoint = $ApiEndpoint -replace '(\?|\&)ids=', '$1activityIds='
      $ApiEndpoint = [pscustomobject]@{GetActivityById = $ByActivityID} | Get-S1Filter -ApiEndpoint $ApiEndpoint
    } elseif ($ByActivityType) { # Specific
      $ApiEndpoint = [pscustomobject]@{GetActivityByActivityType = $ByActivityType} | Get-S1Filter -ApiEndpoint $ApiEndpoint
    } elseif ($InputObject) { # Generic
      if ($InputObject.PSObject.Properties.Name -contains 'threatId') {
        $ApiEndpoint = [pscustomobject]@{GetByThreatId = $InputObject.threatId} | Get-S1Filter -ApiEndpoint $ApiEndpoint
      } elseif ($InputObject.PSObject.Properties.Name -contains 'userId') {
        $ApiEndpoint = [pscustomobject]@{GetByUserId = $InputObject.userId} | Get-S1Filter -ApiEndpoint $ApiEndpoint
      } elseif ($InputObject.GetType() -eq [int]) { # Strings parsed through pipeline, assume they are names
        $ApiEndpoint = [pscustomobject]@{GetActivityById = $InputObject} | Get-S1Filter -ApiEndpoint $ApiEndpoint
      } else {
        $ApiEndpoint = Get-S1Filter -ApiEndpoint $ApiEndpoint -InputObject $InputObject
      }
    }

    $ApiEndpoint = $ApiEndpoint -replace 'activityIds', 'ids'

    # Build
    $functionParameters += @{
      ApiEndpoint = $ApiEndpoint
      ApiVersion  = $ApiVersion
    }

    # Save the command
    if ($SaveCommand) {
      $ApiEndpoint = $ApiEndpoint -replace '(\?|\&)ids=', '$1activityIds='
      $params += [pscustomobject]@{ApiEndpoint = $ApiEndpoint} | Get-S1CommandParameter -Invocation $MyInvocation
      return
    }

    # Error checking is all done in the following function so no extra error checking needs to be done.
    # Calling the function and returning the results instantly helps for better pipeline processing
    Invoke-SentinelOneApiRequest @functionParameters | & { process {
      $result = $_ | Select-Object -Property *,'activityId','activityTypeId'
      $result.activityId = $_.id
      $result.activityTypeId = $_.activityType
      return $result
    }}
  }

  End {
    if ($SaveCommand) {
      Get-S1Command -Command $MyInvocation.MyCommand.Name -Parameters $params
    }
  }
}

#[pscustomobject]@{userId = '1275560511077494534'; groupIds = '1404037872361012638'; agentIds = '1404044446102127871'; siteIds = '1403237978083395984';} | Get-S1Activity

function Get-S1ActivityTypes {
  <#
  .DESCRIPTION
    Get a list of activity types. This is useful to see valid values to filter activities in other commands.
  .SYNOPSIS
    Get a list of activity types.
  .PARAMETER ManagementUrl
    The base URL for the customer's SentinelOne environment
  .PARAMETER Credential
    PSCredential Object containing the API Key in the Password field
 
  .OUTPUTS
    Returns a PSCustomObject containing action Ids, names and description templates
    Returns ErrorObject if an error is encountered
  .EXAMPLE
    Get-S1ActivityTypes -ManagementUrl "apne1-1110-mssp.sentinelone.net" -Credential (Get-PSCredential)
 
  #>

  [CmdletBinding(DefaultParameterSetName = 'All')]
  param(
        [Parameter(Mandatory=$false,
      HelpMessage = 'The base URL for the customers SentinelOne environment')]
    [string] $ManagementUrl,

        [Parameter(Mandatory=$false,
      HelpMessage = 'PSCredential Object containing the API Key in the Password field')]
    [PsCredential] $Credential,


        [Alias('activityTypeId')]
    [Parameter(Mandatory=$false,
      HelpMessage = 'ID of the activity',
      ValueFromPipelineByPropertyName = $true)]
    [int]$ByActivityTypeID,

    [Alias('activityAction')]
    [Parameter(Mandatory=$false,
      HelpMessage = 'Name of the action for the activity',
      ValueFromPipelineByPropertyName = $true)]
    [string]$ByActionName,

    [Parameter(Mandatory=$false,
      HelpMessage = 'Use regex for action name',
      ValueFromPipelineByPropertyName = $true)]
    [switch]$Regex,

    [Parameter(Mandatory=$false,
      HelpMessage = 'Pipeline handler',
      ValueFromPipeline = $true,
      ValueFromRemainingArguments = $true,
      DontShow = $true)]
    [pscustomobject]$InputObject
    )

  Begin {
    $ApiVersion = '2.1'
    $ApiEndpoint = 'activities/types'

    if ($ManagementUrl) {
      $functionParameters += @{
        ManagementUrl = $ManagementUrl
      }
    }

    if ($Credential) {
      $functionParameters += @{
        Credential = $Credential
      }
    }
  }

  Process {

    $functionParameters += @{
      ApiEndpoint = $ApiEndpoint
      ApiVersion  = $ApiVersion
    }

    # API Endpoint does not use pagination
    Invoke-SentinelOneApiRequest @functionParameters | & { process {
      $result = $_ | Select-Object -Property id,action,descriptionTemplate,activityTypeId
      $result.activityTypeId = $_.id
      if ($ByActivityTypeID) {
        return $result | Where-Object { $_.id -eq $ByActivityTypeID }
      } elseif ($ByActionName) {
        if ($Regex) {
          return $result | Where-Object { $_.action -match $ByActionName }
        } else {
          return $result | Where-Object { $_.action -eq $ByActionName }
        }
      } else {
        return $result
      }
    }}
  }
}

# Function that returns a PSCustomObject containing SentinelOne agent data

function Get-S1Agent {
  <#
  .DESCRIPTION
    Get the Agents, and their data, that match the filter. This command gives the Agent ID, which you can use in other commands.
  .SYNOPSIS
    Get the Agents, and their data, that match the filter.
  .PARAMETER ManagementUrl
    The base URL for the customer's SentinelOne environment
  .PARAMETER Credential
    PSCredential Object containing the API Key in the Password field
 
  .PARAMETER Filter
    Filters to apply to the query in hashtable format.
    eg.
    $filters = @{
      groupIds = @(225494730938493804, 225494730938493915)
      sortBy = 'id'
      computerName__like = 'azm'
    }
    Get-S1Agent -Filter $filters
  .PARAMETER ByAgentID
    ID of the SentinelOne agent
  .PARAMETER ByName
    Computer Name with the SentinelOne agent installed
  .PARAMETER ByGroupID
    Group ID containing SentinelOne agents
  .PARAMETER BySiteID
    Site ID containing SentinelOne agent
  .OUTPUTS
    Returns a PSCustomObject containing the Agents and their data
    Returns ErrorObject if an error is encountered
  .EXAMPLE
    Get-S1Agent -ManagementUrl "apne1-1110-mssp.sentinelone.net" -Credential (Get-PSCredential)
 
  #>

  [CmdletBinding(DefaultParameterSetName = 'All')]
  param(
        [Parameter(Mandatory=$false,
      HelpMessage = 'The base URL for the customers SentinelOne environment')]
    [string] $ManagementUrl,

        [Parameter(Mandatory=$false,
      HelpMessage = 'PSCredential Object containing the API Key in the Password field')]
    [PsCredential] $Credential,


        [Parameter(Mandatory=$false,
      HelpMessage = 'Filters to apply to the query in hashtable format.
      eg.
      $filters = @{
        groupIds = [225494730938493804, 225494730938493915]
        sortBy = "id"
        computerName__like = "azm"
      }
      Get-S1Agents -Filter $filters'
)]
    [hashtable] $Filter,

    [Alias('agentId')]
    [Parameter(Mandatory=$false,
      HelpMessage = 'ID of the agent',
      ValueFromPipelineByPropertyName = $true)]
    [string]$ByAgentID,

    [Alias('computerName')]
    [Parameter(Mandatory=$false,
      HelpMessage = 'Name of the computer the agent is installed on',
      #ParameterSetName = 'ByName',
      ValueFromPipelineByPropertyName = $true)]
    [string]$ByName,

    [Parameter(Mandatory = $false)]
    [switch]
    $SaveCommand,

    [Parameter(Mandatory=$false,
      HelpMessage = 'Pipeline handler',
      ValueFromPipeline = $true,
      ValueFromRemainingArguments = $true,
      DontShow = $true)]
    [pscustomobject]$InputObject
    )

  Begin {
    # Use Max Page Size to reduce the number of requests
    $limit = 1000
    $ApiVersion = '2.1'
    $ApiEndpoint = [System.Text.StringBuilder]'agents'

    $Parameters = @()
    $Parameters += ("limit={0}" -f $limit)

    if ($Filter) {
      # An Agent filter was specified
      $Parameters += $Filter.keys | & { process {
        "$_={0}" -f $(if ($Filter.$_.GetType() -eq [Object[]]) {Join-String -Separator "," -InputObject $Filter.$_} else {$Filter.$_})
      }}
    }

    $ParamString = $Parameters -join '&'

    $null = $ApiEndpoint.Append("?")
    $null = $ApiEndpoint.Append($ParamString)
    $ApiEndpoint = $ApiEndpoint.ToString()

    if ($ManagementUrl) {
      $functionParameters += @{
        ManagementUrl = $ManagementUrl
      }
    }

    if ($Credential) {
      $functionParameters += @{
        Credential = $Credential
      }
    }
  }

  Process {

    if ($ByAgentID) { # Specific
      $ApiEndpoint = $ApiEndpoint -replace '(\?|\&)ids=', '$1agentIds='
      $ApiEndpoint = [pscustomobject]@{agentId = $ByAgentID} | Get-S1Filter -ApiEndpoint $ApiEndpoint
    } elseif ($ByName) { # Specific
      $ApiEndpoint = [pscustomobject]@{GetAgentByComputerName = $ByName} | Get-S1Filter -ApiEndpoint $ApiEndpoint
    } elseif ($InputObject) { # Generic
      if ($InputObject.GetType() -eq [string]) { # Strings parsed through pipeline, assume they are names
        $ApiEndpoint = [pscustomobject]@{GetAgentByComputerName = $InputObject} | Get-S1Filter -ApiEndpoint $ApiEndpoint
      } else {
        $ApiEndpoint = Get-S1Filter -ApiEndpoint $ApiEndpoint -InputObject $InputObject
      }
    }

    $ApiEndpoint = $ApiEndpoint -replace 'agentIds', 'ids'

    # Build
    $functionParameters += @{
      ApiEndpoint = $ApiEndpoint
      ApiVersion  = $ApiVersion
    }

    # Save the command
    if ($SaveCommand) {
      $ApiEndpoint = $ApiEndpoint -replace '(\?|\&)ids=', '$1agentIds='
      $ApiEndpoint = $ApiEndpoint -replace "(\?|\&)(agentIds=[^&]+)",'$1'
      $ApiEndpoint = $ApiEndpoint -replace "(\?|\&)(computerName=[^&]+)",'$1'
      $params += [pscustomobject]@{ApiEndpoint = $ApiEndpoint} | Get-S1CommandParameter -Invocation $MyInvocation
      return
    }

    # Error checking is all done in the following function so no extra error checking needs to be done.
    # Calling the function and returning the results instantly helps for better pipeline processing
    Invoke-SentinelOneApiRequest @functionParameters | & { process {
      $result = $_ | Select-Object -Property *,'agentId'
      $result.agentId = $_.id
      return $result
    }}
  }

  End {
    if ($SaveCommand) {
      Get-S1Command -Command $MyInvocation.MyCommand.Name -Parameters $params
    }
  }
}

# Function to get the count of Agents that match a filter.

function Get-S1AgentCount {
  <#
  .DESCRIPTION
    Get the count of Agents that match a filter. This command is useful to run before you run other commands. You will be able to manage Agent maintenance better if you know how many Agents will get a command that takes time (such as Update Software).
  .SYNOPSIS
    Get the count of Agents that match a filter.
  .PARAMETER ManagementUrl
    The base URL for the customer's SentinelOne environment
  .PARAMETER Credential
    PSCredential Object containing the API Key in the Password field
 
  .PARAMETER Filter
    Filters to apply to the query in hashtable format.
    eg.
    $filters = @{
      groupIds = @(225494730938493804, 225494730938493915)
      sortBy = 'id'
      computerName__like = 'azm'
    }
    Get-S1AgentCount -Filter $filters
  .OUTPUTS
    Returns a PSCustomObject containing the number of agents matching the criteria
    Returns ErrorObject if an error is encountered
  .EXAMPLE
    Get-S1AgentCount -ManagementUrl "apne1-1110-mssp.sentinelone.net" -Credential (Get-PSCredential)
 
  #>

  [CmdletBinding(DefaultParameterSetName = 'All')]
  param(
        [Parameter(Mandatory=$false,
      HelpMessage = 'The base URL for the customers SentinelOne environment')]
    [string] $ManagementUrl,

        [Parameter(Mandatory=$false,
      HelpMessage = 'PSCredential Object containing the API Key in the Password field')]
    [PsCredential] $Credential,


        [Parameter(Mandatory=$false,
      HelpMessage = 'Filters to apply to the query in hashtable format.
      eg.
      $filters = @{
        groupIds = @(225494730938493804, 225494730938493915)
        sortBy = "id"
        computerName__like = "azm"
      }
      Get-S1AgentCount -Filter $filters'
)]
    [hashtable] $Filter,

    [Parameter(Mandatory=$false,
      HelpMessage = 'Pipeline handler',
      ValueFromPipeline = $true,
      ValueFromRemainingArguments = $true,
      DontShow = $true)]
    [pscustomobject]$InputObject
    )

  Begin {
    # Use Max Page Size to reduce the number of requests
    #$limit = 1000
    $ApiVersion = '2.1'
    $ApiEndpoint = [System.Text.StringBuilder]'agents/count'

    $Parameters = @()
    #$Parameters += ("limit={0}" -f $limit)

    if ($Filter) {
      # An Agent filter was specified
      $Parameters += $Filter.keys | & { process {
        "$_={0}" -f $(if ($Filter.$_.GetType() -eq [Object[]]) {Join-String -Separator "," -InputObject $Filter.$_} else {$Filter.$_})
      }}
    }

    $ParamString = $Parameters -join '&'

    $null = $ApiEndpoint.Append("?")
    $null = $ApiEndpoint.Append($ParamString)
    $ApiEndpoint = $ApiEndpoint.ToString()

    if ($ManagementUrl) {
      $functionParameters += @{
        ManagementUrl = $ManagementUrl
      }
    }

    if ($Credential) {
      $functionParameters += @{
        Credential = $Credential
      }
    }

    $AgentCount = 0
  }

  Process {
    if ($InputObject) { # Generic
      if (($InputObject | Get-Member -MemberType Properties).Name -contains 'agentId') { # No need for an api call
        $AgentCount += $InputObject.agentId.Count
        return
      }
      $ApiEndpoint = Get-S1Filter -ApiEndpoint $ApiEndpoint -InputObject $InputObject
      $ApiEndpoint = $ApiEndpoint -replace 'computerName=','computerName__like='
      $ApiEndpoint = $ApiEndpoint -replace '(\?|&)agentIds=[^&]+',''
    }

    $functionParameters += @{
      ApiEndpoint = $ApiEndpoint
      ApiVersion  = $ApiVersion
    }

    # API Call to get the tag
    $AgentCountResponse = Invoke-SentinelOneApiRequest @functionParameters

    if ($AgentCountResponse -is [HashTable] -and $AgentCountResponse.Error) {
      Write-Error -Message "Error calling Agents API. Response Code: $($AgentCountResponse.Code) Note: $($AgentCountResponse.Note)" -ErrorId $AgentCountResponse.Code -CategoryReason $AgentCountResponse.Note
      return $AgentCountResponse
    }

    $AgentCount += $AgentCountResponse.total
  }

  End {
    [pscustomobject]@{total = $AgentCount}
  }
}

function Invoke-SentinelOneApiRequest {
  <#
  .SYNOPSIS
    Invoke the SentinelOne API
  .DESCRIPTION
    This function is intended to be called by other functions for specific resources/interactions
  .PARAMETER Uri
    Base API URL for the API Call
  .PARAMETER Credential
    PSCredential Object with the API Key stored in the Password property of the object.
  .PARAMETER Method
    Valid HTTP Method to use: GET (Default), POST, DELETE, PUT
  .PARAMETER Body
    PSCustomObject containing data to be sent as HTTP Request Body in JSON format.
  .PARAMETER Depth
    How deep are we going?
  .PARAMETER Cursor
    See next page of unknown number of items.
  .OUTPUTS
    PSCustomObject containing results if successful. May be $null if no data is returned
    ErrorObject containing details of error if one is encountered.
  #>

  [CmdletBinding()]

  param(
    [Parameter(Mandatory=$true,
      HelpMessage = 'API endpoint eg. agents/count')]
    [string]  $ApiEndpoint,

    [Parameter(Mandatory=$false,
      HelpMessage = 'The base URL for the customers SentinelOne environment')]
      [ValidateScript({
        $TypeName = $_ | Get-Member | Select-Object -ExpandProperty TypeName -Unique
        if ($TypeName -eq 'System.String' -or $TypeName -eq 'System.UriBuilder') {
          [System.UriBuilder]$_
        }
      })]
    [System.UriBuilder] $ManagementUrl,

    [Parameter(Mandatory=$false,
      HelpMessage = 'The Api Version to use')]
    [float] $ApiVersion,

    [Parameter(Mandatory=$false,
      HelpMessage = 'PSCredential Object containing the API Key in the Password property')]
    [PSCredential]  $Credential,

    [Parameter(Mandatory=$false,
      HelpMessage = 'Method to use when making the request. Defaults to GET')]
    [ValidateSet("Post","Get","Put","Delete")]
    [string] $Method = "GET",

    [Parameter(Mandatory=$false,
      HelpMessage = 'PsCustomObject containing data that will be sent as the Json Body')]
    [PsCustomObject] $Body,

    [Parameter(Mandatory=$false,
      HelpMessage = 'How deep are we?')]
    [int] $Depth = 0,

    [Parameter(Mandatory=$false,
      HelpMessage = 'See next page of unknown number of items.')]
    [string] $Cursor
    )

  Begin {
    $Me = $MyInvocation.MyCommand.Name

    Write-Verbose $Me

    # Setup Error Object structure
    $ErrorObject = @{
      Code                  =   $null
      Error                 =   $false
      Type                  =   $null
      Note                  =   $null
      Raw                   =   $_
    }

    # Import config
    if (($PSBoundParameters.ContainsKey('ManagementUrl')) -and ($PSBoundParameters.ContainsKey('ApiVersion')) -and ($PSBoundParameters.ContainsKey('Credential'))) {
      $config = [pscustomobject]@{
        managementUrl = $null
        apiVersion = $null
        credential = $null
      }
    } else {
      $config = Get-SentinelOneConfig
    }

    # Use parameters if set
    if ($PSBoundParameters.ContainsKey('ManagementUrl')) {
      $config.managementUrl = $ManagementUrl.Host
    }

    if ($PSBoundParameters.ContainsKey('ApiVersion')) {
      $config.apiVersion = $ApiVersion
    }

    if ($PSBoundParameters.ContainsKey('Credential')) {
      $config.credential = $Credential
    }

    Write-Debug ("Config compiled: {0}" -f $config)

    # Build URI
    $Uri = [System.UriBuilder]("https://{0}/web/api/v{1}/{2}" -f $config.managementUrl, $config.apiVersion, $ApiEndpoint)

    if (($Method -eq 'GET') -and $Body) {
      throw "Cannot specify Request Body for Method GET."
    }

    $Header = @{}
    $ApiKey = $config.credential.GetNetworkCredential().Password
    $Header.Add('Authorization', ("ApiToken {0}" -f $ApiKey))
    $Header.Add('Content-Type', 'application/json')

    # Buld Rest Method parameters
    $params = @{
      Method                  = $Method
      Uri                     = $Uri.Uri
      Headers                 = $Header
      ResponseHeadersVariable = 'ResponseHeaders'
      ContentType             = 'application/json'
    }

    # Add body if present
    if ($Body) {
      Write-Verbose "$Me : Body supplied"
      $params += @{
        Body = $($Body | ConvertTo-Json -Depth 15)
      }
    }

    # Add cursor if present
    if ($Cursor) {
      Write-Verbose "$Me : Cursor supplied"

      $pattern = "^(.*cursor=)([^&]+)(.*)$"
      if ($Uri.Uri -match $pattern) {
        $params.Uri = ($Uri.Uri -replace $pattern,('$1{0}$3' -f $Cursor))
      } else {
        $params.Uri = ('{0}{1}cursor={2}' -f $Uri.Uri, $(if ($Uri.Query.IndexOf('?') -eq 0) {"&"} else {"?"}), $Cursor)
      }
    }

    Write-Debug "Parameters: $($params | ConvertTo-Json -Depth 15)"
  }

  Process {
    $Results = $null

    # Enforce TLSv1.2
    [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12

    # Code to make the API Call. Used: $Results,$ResponseHeaders = Invoke-Command -ScriptBlock $apiCallCode -- this is to remove code duplication
    $apiCallCode = {
      try {
        $Results = Invoke-RestMethod @params
      } catch {
        $Exception = $_.Exception
        Write-Verbose "$Me : Exception : $($Exception.Response.StatusCode)"
        $ErrorObject.Error = $true
        $ErrorObject.Code = $Exception.Response.StatusCode
        $ErrorObject.Note = $Exception.Message
        $ErrorObject.Raw = $Exception
        Write-Debug ($ErrorObject | ConvertTo-Json -Depth 3)

        return $ErrorObject,$null
      }
      Write-Debug ($ResponseHeaders | ConvertTo-Json -Depth 3)
      Write-Debug ($Results | ConvertTo-Json -Depth 15)

      return $Results,$ResponseHeaders
    }

    $processResults = {
      if ($Results -is [HashTable] -and $Results.ContainsKey('Error') -and $Results.Error) {
        Write-Debug ($Results | ConvertTo-Json)
        Write-Output $Results
        Write-Error "$Me : Encountered error getting additional results. $($ErrorObject.Code) : $($ErrorObject.Note)"
      } else {
        Write-Output $Results.data
      }
    }

    $Results,$ResponseHeaders = Invoke-Command -ScriptBlock $apiCallCode
    Invoke-Command -ScriptBlock $processResults

    # Check if we have a cursor to more results
    if (($Results | Get-Member | Select-Object -ExcludeProperty Name -Unique) -match "pagination" -and $null -ne $Results.pagination.nextCursor) {
      do {
        $Cursor = $Results.pagination.nextCursor
        $params.Uri = ('{0}{1}cursor={2}' -f $Uri.Uri, $(if ($Uri.Query.IndexOf('?') -eq 0) {"&"} else {"?"}), $Cursor)

        $Results,$ResponseHeaders = Invoke-Command -ScriptBlock $apiCallCode
        Invoke-Command -ScriptBlock $processResults
      } while ($null -ne $Results.pagination.nextCursor)
    }
  }

  End {
    Write-Verbose "Clearing variables"
    $Credential = $null
    Remove-Variable -Name config
    Remove-Variable -Name Credential
    Remove-Variable -Name Results
    Remove-Variable -Name ErrorObject
    $pattern = $null
    Remove-Variable -Name pattern
    Remove-Variable -Name ResponseHeaders
    Remove-Variable -Name apiCallCode
    Remove-Variable -Name processResults
    return
  }
}

# Function that returns a PSCustomObject containing SentinelOne group data

function Get-S1Group {
  <#
  .DESCRIPTION
    Get the SentinelOne groups that match the filter.
  .SYNOPSIS
    Get the SentinelOne groups that match the filter.
  .PARAMETER ManagementUrl
    The base URL for the customer's SentinelOne environment
  .PARAMETER Credential
    PSCredential Object containing the API Key in the Password field
 
  .PARAMETER Filter
    Filters to apply to the query in hashtable format.
    eg.
    $filters = @{
      groupIds = @(225494730938493804, 225494730938493915)
      sortBy = 'id'
      computerName__like = 'azm'
    }
    Get-S1Agent -Filter $filters
  .PARAMETER ByGroupID
    Group ID
  .PARAMETER ByName
    Exact match of the group name
  .PARAMETER ByRegistrationToken
    Find groups matching a registration token
  .OUTPUTS
    Returns a PSCustomObject containing the groups and its data
    Returns ErrorObject if an error is encountered
  .EXAMPLE
    Get-S1Group
 
  #>

  [CmdletBinding(DefaultParameterSetName = 'All')]
  param(
        [Parameter(Mandatory=$false,
      HelpMessage = 'The base URL for the customers SentinelOne environment')]
    [string] $ManagementUrl,

        [Parameter(Mandatory=$false,
      HelpMessage = 'PSCredential Object containing the API Key in the Password field')]
    [PsCredential] $Credential,


        [Parameter(Mandatory=$false,
      HelpMessage = 'Filters to apply to the query in hashtable format.
      eg.
      $filters = @{
        groupIds = [225494730938493804, 225494730938493915]
        sortBy = "id"
        computerName__like = "azm"
      }
      Get-S1Agents -Filter $filters'
)]
    [hashtable] $Filter,

    [Alias('groupId')]
    [Parameter(Mandatory=$false,
      HelpMessage = 'ID of the group',
      ValueFromPipelineByPropertyName = $true)]
    [string]$ByGroupID,

    [Alias('groupName')]
    [Parameter(Mandatory=$false,
      HelpMessage = 'Name of the SentinelOne group',
      ValueFromPipelineByPropertyName = $true)]
    [string]$ByName,

    [Alias('registrationToken')]
    [Parameter(Mandatory=$false,
      HelpMessage = 'Find groups matching a registration token',
      ValueFromPipelineByPropertyName = $true)]
    [string]$ByRegistrationToken,

    [Parameter(Mandatory = $false)]
    [switch]
    $SaveCommand,

    [Parameter(Mandatory=$false,
      HelpMessage = 'Pipeline handler',
      ValueFromPipeline = $true,
      ValueFromRemainingArguments = $true,
      DontShow = $true)]
    [pscustomobject]$InputObject
    )

  Begin {
    # Use Max Page Size to reduce the number of requests
    $limit = 200
    $ApiVersion = '2.1'
    $ApiEndpoint = [System.Text.StringBuilder]'groups'

    $Parameters = @()
    $Parameters += ("limit={0}" -f $limit)

    if ($Filter) {
      # An Agent filter was specified
      $Parameters += $Filter.keys | & { process {
        "$_={0}" -f $(if ($Filter.$_.GetType() -eq [Object[]]) {Join-String -Separator "," -InputObject $Filter.$_} else {$Filter.$_})
      }}
    }

    $ParamString = $Parameters -join '&'

    $null = $ApiEndpoint.Append("?")
    $null = $ApiEndpoint.Append($ParamString)
    $ApiEndpoint = $ApiEndpoint.ToString()

    if ($ManagementUrl) {
      $functionParameters += @{
        ManagementUrl = $ManagementUrl
      }
    }

    if ($Credential) {
      $functionParameters += @{
        Credential = $Credential
      }
    }
  }

  Process {

    if ($ByName) { # Specific
      $ApiEndpoint = [pscustomobject]@{GetByName = $ByName} | Get-S1Filter -ApiEndpoint $ApiEndpoint
    } elseif($ByRegistrationToken -and ('state' -notin (($InputObject | Get-Member -MemberType Properties).Name))) { # Specific
      $ApiEndpoint = [pscustomobject]@{GetByRegistrationToken = $ByRegistrationToken} | Get-S1Filter -ApiEndpoint $ApiEndpoint
    } elseif ($InputObject) { # Generic
      $ApiEndpoint = Get-S1Filter -ApiEndpoint $ApiEndpoint -InputObject $InputObject
    }

    $ApiEndpoint = $ApiEndpoint -replace '(\?|\&)(agentIds=[^&]+)','$1'

    # Save the command
    if ($SaveCommand) {
      $ApiEndpoint = $ApiEndpoint -replace "(\?|\&)(registrationToken=[^&]+)",'$1'
      $ApiEndpoint = $ApiEndpoint -replace "(\?|\&)(groupIds=[^&]+)",'$1'
      $params += [pscustomobject]@{ApiEndpoint = $ApiEndpoint} | Get-S1CommandParameter -Invocation $MyInvocation
      return
    }

    # ByGroupID? overwrite endpoint
    if ($ByGroupID) { # Specific
      $ApiEndpoint = "groups/$ByGroupID"
    }

    $functionParameters += @{
      ApiEndpoint = $ApiEndpoint
      ApiVersion  = $ApiVersion
    }

    # Error checking is all done in the following function so no extra error checking needs to be done.
    # Calling the function and returning the results instantly helps for better pipeline processing
    Invoke-SentinelOneApiRequest @functionParameters | & { process {
      $result = $_ | Select-Object -Property *,'groupId'
      $result.groupId = $_.id
      return $result
    }}
  }

  End {
    if ($SaveCommand) {
      Get-S1Command -Command $MyInvocation.MyCommand.Name -Parameters $params
    }
  }
}

function New-SentinelOneConfig {
  [CmdletBinding(SupportsShouldProcess = $true)]
  param(
    [Parameter(Mandatory=$true,
      HelpMessage = 'The base URL for the customers SentinelOne environment')]
    [System.UriBuilder] $ManagementUrl,

    [Parameter(Mandatory=$true,
      HelpMessage = 'The Api Version to use')]
    [float] $ApiVersion,

    [Parameter(Mandatory=$true,
      HelpMessage = 'PSCredential Object containing the API Key in the Password field')]
    [pscredential] $Credential,

    [Parameter(Mandatory=$false,
      HelpMessage = 'Local app data folder name')]
    [string] $ConfigFolderName,

    [Parameter(Mandatory=$false,
      HelpMessage = 'XML config file name')]
    [string] $ConfigFileName
  )

  Begin {
    Write-Verbose "Creating config file"

    if (!$PSBoundParameters.ContainsKey('ConfigFolderName')) {
      $ConfigFolderName = "SentinelOne.Tools"
    }

    if (!$PSBoundParameters.ContainsKey('ConfigFileName')) {
      $ConfigFileName = "SentinelOne.Tools.xml"
    }

    # Define variables
    $configFileFolder = [io.path]::combine($ENV:LOCALAPPDATA, $ConfigFolderName)
    $configFile = [io.path]::combine($configFileFolder, $ConfigFileName)

    Write-Debug ("Received input:
    ManagementUrl: {0}
    ApiVersion: {1}
    Credential: {2}"
 -f $ManagementUrl, $ApiVersion, $Credential)

    Write-Verbose ("Config file location: {0}" -f $configFile)
    # Check if folder / config file exists
    if (!(Test-Path -Path $configFileFolder)) {
      # Folder does not exist
      Write-Verbose ("Config folder does not exist. Creating: {0}" -f $configFileFolder)
      if ($PSCmdlet.ShouldProcess((Split-Path -Parent -Path $configFileFolder), ("Creating folder '{0}'" -f (Split-Path -Leaf -Path $configFileFolder)))) {
        New-Item -Path $configFileFolder -ItemType Directory -Force | Out-Null
      } else {
        # Don't do anything
      }
    }
  }

  Process {

    $config = [pscustomobject]@{
      managementUrl = $ManagementUrl.Host
      apiVersion = $ApiVersion
      credential = $Credential
    }

    Write-Debug ("Config compiled: {0}" -f $config)

    # Create the config file
    if ($PSCmdlet.ShouldProcess((Split-Path -Parent -Path $configFile), ("Creating config file '{0}'" -f (Split-Path -Leaf -Path $configFile)))) {
      $config | Export-Clixml -Path $configFile -Force | Out-Null
    } else {
      # Don't do anything
    }

    Write-Verbose ("Config saved: {0}" -f $configFile)
  }

  End {
    $config = $null
    Remove-Variable -Name config
  }
}

# Function that returns a PSCustomObject containing SentinelOne site data

function Get-S1Site {
  <#
  .DESCRIPTION
    Get the Agents, and their data, that match the filter. This command gives the Agent ID, which you can use in other commands.
  .SYNOPSIS
    Get the Agents, and their data, that match the filter.
  .PARAMETER ManagementUrl
    The base URL for the customer's SentinelOne environment
  .PARAMETER Credential
    PSCredential Object containing the API Key in the Password field
 
  .PARAMETER Filter
    Filters to apply to the query in hashtable format.
    eg.
    $filters = @{
      groupIds = @(225494730938493804, 225494730938493915)
      sortBy = 'id'
      computerName__like = 'azm'
    }
    Get-S1Agent -Filter $filters
  .PARAMETER BySiteID
    Site ID
  .PARAMETER ByName
    Exact match of the site name
  .PARAMETER ByRegistrationToken
    Find sites matching a registration token
  .PARAMETER SiteType
    Site types: (Paid or Trial)
  .PARAMETER State
    Site states: (Active, Deleted, Expired)
  .OUTPUTS
    Returns a PSCustomObject containing the sites and its data
    Returns ErrorObject if an error is encountered
  .EXAMPLE
    Get-S1Site -ByType Trial
 
  #>

  [CmdletBinding(DefaultParameterSetName = 'All')]
  param(
        [Parameter(Mandatory=$false,
      HelpMessage = 'The base URL for the customers SentinelOne environment')]
    [string] $ManagementUrl,

        [Parameter(Mandatory=$false,
      HelpMessage = 'PSCredential Object containing the API Key in the Password field')]
    [PsCredential] $Credential,


        [Parameter(Mandatory=$false,
      HelpMessage = 'Filters to apply to the query in hashtable format.
      eg.
      $filters = @{
        groupIds = [225494730938493804, 225494730938493915]
        sortBy = "id"
        computerName__like = "azm"
      }
      Get-S1Agents -Filter $filters'
)]
    [hashtable] $Filter,

    [Alias('siteId')]
    [Parameter(Mandatory=$false,
      HelpMessage = 'ID of the site',
      ValueFromPipelineByPropertyName = $true)]
    [string]$BySiteID,

    [Alias('siteName')]
    [Parameter(Mandatory=$false,
      HelpMessage = 'Name of the SentinelOne site',
      ValueFromPipelineByPropertyName = $true)]
    [string]$ByName,

    [Alias('registrationToken')]
    [Parameter(Mandatory=$false,
      HelpMessage = 'Find sites matching a registration token',
      ValueFromPipelineByPropertyName = $true)]
    [string]$ByRegistrationToken,

    [Parameter(Mandatory=$false,
      HelpMessage = 'Find sites by site type (Paid or Trial)',
      ValueFromPipelineByPropertyName = $true)]
    [ValidateSet('Paid', 'Trial')]
    [string]$SiteType,

    [Parameter(Mandatory=$false,
      HelpMessage = 'Site states: (Active, Deleted, Expired)',
      ValueFromPipelineByPropertyName = $true)]
    [ValidateSet('Active', 'Deleted', 'Expired')]
    [string]$State,

    [Parameter(Mandatory = $false)]
    [switch]
    $SaveCommand,

    [Parameter(Mandatory=$false,
      HelpMessage = 'Pipeline handler',
      ValueFromPipeline = $true,
      ValueFromRemainingArguments = $true,
      DontShow = $true)]
    [pscustomobject]$InputObject

    )

  Begin {
    # Use Max Page Size to reduce the number of requests
    $limit = 1000
    $ApiVersion = '2.1'
    $ApiEndpoint = [System.Text.StringBuilder]'sites'

    $Parameters = @()
    $Parameters += ("limit={0}" -f $limit)

    if ($Filter) {
      # An Agent filter was specified
      $Parameters += $Filter.keys | & { process {
        "$_={0}" -f $(if ($Filter.$_.GetType() -eq [Object[]]) {Join-String -Separator "," -InputObject $Filter.$_} else {$Filter.$_})
      }}
    }

    $ParamString = $Parameters -join '&'

    $null = $ApiEndpoint.Append("?")
    $null = $ApiEndpoint.Append($ParamString)
    $ApiEndpoint = $ApiEndpoint.ToString()

    if ($ManagementUrl) {
      $functionParameters += @{
        ManagementUrl = $ManagementUrl
      }
    }

    if ($Credential) {
      $functionParameters += @{
        Credential = $Credential
      }
    }
  }

  Process {

    # Filter options
    if ($SiteType) {
      $ApiEndpoint = [pscustomobject]@{GetSiteByType = $SiteType} | Get-S1Filter -ApiEndpoint $ApiEndpoint
    }

    if ($State) {
      $ApiEndpoint = [pscustomobject]@{GetSiteByState = $State} | Get-S1Filter -ApiEndpoint $ApiEndpoint
    }

    if ($ByName) { # Specific
      $ApiEndpoint = [pscustomobject]@{GetByName = $ByName} | Get-S1Filter -ApiEndpoint $ApiEndpoint
    } elseif($ByRegistrationToken) { # Specific
      $ApiEndpoint = [pscustomobject]@{GetByRegistrationToken = $ByRegistrationToken} | Get-S1Filter -ApiEndpoint $ApiEndpoint
    } elseif ($InputObject) { # Generic
      if ($InputObject.GetType() -eq [string]) {
        $ApiEndpoint = [pscustomobject]@{GetByName = $InputObject} | Get-S1Filter -ApiEndpoint $ApiEndpoint
      } else {
        $ApiEndpoint = Get-S1Filter -ApiEndpoint $ApiEndpoint -InputObject $InputObject
      }
    }

    $ApiEndpoint = $ApiEndpoint -replace "(\?|\&)(agentIds=[^&]+)",'$1'

    Write-Debug $ApiEndpoint

    # Save the command
    if ($SaveCommand) {
      $ApiEndpoint = $ApiEndpoint -replace "(\?|\&)(registrationToken=[^&]+)",'$1'
      $params += [pscustomobject]@{ApiEndpoint = $ApiEndpoint} | Get-S1CommandParameter -Invocation $MyInvocation
      return
    }

    # BySiteID? overwrite endpoint
    if ($BySiteID) { # Specific
      $ApiEndpoint = "sites/$BySiteID"
    }

    $functionParameters += @{
      ApiEndpoint = $ApiEndpoint
      ApiVersion  = $ApiVersion
    }

    # Error checking is all done in the following function so no extra error checking needs to be done.
    # Calling the function and returning the results instantly helps for better pipeline processing
    Invoke-SentinelOneApiRequest @functionParameters | & { process {
      if ($BySiteID) {
        $result = $_ | Select-Object -Property *,'siteId','siteName'
        $result.siteId = $_.id
        $result.siteName = $_.name
        return $result
      } else {
        $result = $_.sites | Select-Object -Property *,'siteId','siteName'
        $result | & { process {
          $_.siteId = $_.id
          $_.siteName = $_.name
          return $_
        }}
      }
    }}
  }

  End {
    if ($SaveCommand) {
      Get-S1Command -Command $MyInvocation.MyCommand.Name -Parameters $params
    }
  }
}

# Function that returns a PSCustomObject containing SentinelOne threat data

function Get-S1Threat {
  <#
  .DESCRIPTION
    Get data of threats that match the filter.
  .SYNOPSIS
    Get data of threats
  .PARAMETER ManagementUrl
    The base URL for the customer's SentinelOne environment
  .PARAMETER Credential
    PSCredential Object containing the API Key in the Password field
 
  .PARAMETER Filter
    Filters to apply to the query in hashtable format.
    eg.
    $filters = @{
      groupIds = @(225494730938493804, 225494730938493915)
      sortBy = 'id'
      computerName__like = 'azm'
    }
    Get-S1Threat -Filter $filters
  .OUTPUTS
    Returns a PSCustomObject containing threat data
    Returns ErrorObject if an error is encountered
  .EXAMPLE
    Get-S1Threat -ManagementUrl "apne1-1110-mssp.sentinelone.net" -Credential (Get-PSCredential)
 
  #>

  [CmdletBinding(DefaultParameterSetName = 'All')]
  param(
        [Parameter(Mandatory=$false,
      HelpMessage = 'The base URL for the customers SentinelOne environment')]
    [string] $ManagementUrl,

        [Parameter(Mandatory=$false,
      HelpMessage = 'PSCredential Object containing the API Key in the Password field')]
    [PsCredential] $Credential,


        [Parameter(Mandatory=$false,
      HelpMessage = 'Filters to apply to the query in hashtable format.
      eg.
      $filters = @{
        groupIds = @(225494730938493804, 225494730938493915)
        sortBy = "id"
        computerName__like = "azm"
      }
      Get-S1Agents -Filter $filters'
)]
    [hashtable] $Filter,

    [Alias('threatId')]
    [Parameter(Mandatory=$false,
      HelpMessage = 'Threat ID',
      #ParameterSetName = 'ByThreatID',
      ValueFromPipelineByPropertyName = $true)]
    [string]$ByThreatID,

    # [Alias('agentId')]
    # [Parameter(Mandatory=$false,
    # HelpMessage = 'ID of the agent the threats belong to',
    # #ParameterSetName = 'ByAgentID',
    # ValueFromPipelineByPropertyName = $true)]
    # [string]$ByAgentID,

    # [Alias('groupId')]
    # [Parameter(Mandatory=$false,
    # HelpMessage = 'Group ID of the agents the threats belong to',
    # #ParameterSetName = 'ByGroupID',
    # ValueFromPipelineByPropertyName = $true)]
    # [string]$ByGroupID,

    # [Alias('siteId')]
    # [Parameter(Mandatory=$false,
    # HelpMessage = 'Site ID of the agents the threats belong to',
    # #ParameterSetName = 'BySiteID',
    # ValueFromPipelineByPropertyName = $true)]
    # [string]$BySiteID

    [Parameter(Mandatory = $false)]
    [switch]
    $SaveCommand,

    [Parameter(Mandatory = $false)]
    [switch]
    $NotMitigated,

    [Parameter(Mandatory = $false)]
    [switch]
    $FailedMitigation,

    [Parameter(Mandatory=$false,
      HelpMessage = 'Pipeline handler',
      ValueFromPipeline = $true,
      ValueFromRemainingArguments = $true,
      DontShow = $true)]
    [pscustomobject]$InputObject

    )

  Begin {
    # Use Max Page Size to reduce the number of requests
    $limit = 1000
    $ApiVersion = '2.1'
    $ApiEndpoint = [System.Text.StringBuilder]'threats'

    $Parameters = @()
    $Parameters += ("limit={0}" -f $limit)

    if ($Filter) {
      # An Agent filter was specified
      $Parameters += $Filter.keys | & { process {
        "$_={0}" -f $(if ($Filter.$_.GetType() -eq [Object[]]) {Join-String -Separator "," -InputObject $Filter.$_} else {$Filter.$_})
      }}
    }

    $ParamString = $Parameters -join '&'

    $null = $ApiEndpoint.Append("?")
    $null = $ApiEndpoint.Append($ParamString)
    $ApiEndpoint = $ApiEndpoint.ToString()

    if ($ManagementUrl) {
      $functionParameters += @{
        ManagementUrl = $ManagementUrl
      }
    }

    if ($Credential) {
      $functionParameters += @{
        Credential = $Credential
      }
    }
  }

  Process {
    if ($ByThreatID) {
      $ApiEndpoint = $ApiEndpoint -replace '(\?|\&)ids=', '$1threatIds='
      $ApiEndpoint = [pscustomobject]@{GetByThreatId = $ByThreatID} | Get-S1Filter -ApiEndpoint $ApiEndpoint
      $ApiEndpoint = $ApiEndpoint -replace 'threatIds', 'ids'
    } elseif ($InputObject) {
      $ApiEndpoint = Get-S1Filter -ApiEndpoint $ApiEndpoint -InputObject $InputObject
    }

    $functionParameters += @{
      ApiEndpoint = $ApiEndpoint
      ApiVersion  = $ApiVersion
    }

    # Save the command
    if ($SaveCommand) {
      $ApiEndpoint = $ApiEndpoint -replace '(\?|\&)ids=', '$1threatIds='
      if ($ByThreatID -and ($ApiEndpoint -match "(\?|\&)(threatIds=[^&]+)")) {
        if ($Matches[1] -eq '?') {
          $ApiEndpoint = $ApiEndpoint -replace "(\?|\&)(threatIds=[^&]+)",'?'
        } else {
          $ApiEndpoint = $ApiEndpoint -replace "(\?|\&)(threatIds=[^&]+)",''
        }
      }
      $params += [pscustomobject]@{ApiEndpoint = $ApiEndpoint} | Get-S1CommandParameter -Invocation $MyInvocation
      return
    }

    # Error checking is all done in the following function so no extra error checking needs to be done.
    # Calling the function and returning the results instantly helps for better pipeline processing
    Invoke-SentinelOneApiRequest @functionParameters | & { process {
      $result = $_ | Select-Object -Property *,'threatId','storylineId','agentId','siteId','groupId'
      $result.threatId = $_.id
      $result.storylineId = $_.threatInfo.storyline
      $result.agentId = $_.agentRealtimeInfo.agentId
      $result.siteId = $_.agentRealtimeInfo.siteId
      $result.groupId = $_.agentRealtimeInfo.groupId
      return $result
    }} | & { process {
      if ($NotMitigated -or $FailedMitigation) {
        if ($NotMitigated -and ($_.threatInfo.mitigationStatus -eq 'not_mitigated')) {
          return $_
        } elseif ($FailedMitigation -and ($_.mitigationStatus.status -match 'failed')) {
          return $_
        }
      } else {
        return $_
      }
    }}
  }

  End {
    if ($SaveCommand) {
      Get-S1Command -Command $MyInvocation.MyCommand.Name -Parameters $params
    }
  }
}

Get-S1Threat -ManagementUrl 'apne1-1110-mssp.sentinelone.net' -Credential $c

function Get-S1User {
  <#
  .DESCRIPTION
    Get a list of users or a given user by ID.
  .SYNOPSIS
    Get a list of users or a given user by ID.
  .PARAMETER ManagementUrl
    The base URL for the customer's SentinelOne environment
  .PARAMETER Credential
    PSCredential Object containing the API Key in the Password field
 
  .PARAMETER Filter
    Filters to apply to the query in hashtable format.
    eg.
    $filters = @{
      groupIds = @(225494730938493804, 225494730938493915)
      sortBy = 'id'
    }
    Get-S1User -Filter $filters
  .PARAMETER ByUserID
    ID of the user
  .PARAMETER ByUserEmail
    Email of the user to find
  .OUTPUTS
    Returns a PSCustomObject containing the User(s)
    Returns ErrorObject if an error is encountered
  .EXAMPLE
    Get-S1User -ManagementUrl "apne1-1110-mssp.sentinelone.net" -Credential (Get-PSCredential)
 
  #>

  [CmdletBinding(DefaultParameterSetName = 'All')]
  param(
        [Parameter(Mandatory=$false,
      HelpMessage = 'The base URL for the customers SentinelOne environment')]
    [string] $ManagementUrl,

        [Parameter(Mandatory=$false,
      HelpMessage = 'PSCredential Object containing the API Key in the Password field')]
    [PsCredential] $Credential,


        [Parameter(Mandatory=$false,
      HelpMessage = 'Filters to apply to the query in hashtable format.
      eg.
      $filters = @{
        groupIds = @(225494730938493804, 225494730938493915)
        sortBy = "id"
      }
      Get-S1User -Filter $filters'
)]
    [hashtable] $Filter,

    [Alias('userId')]
    [Parameter(Mandatory=$false,
      HelpMessage = 'ID of the user',
      ValueFromPipelineByPropertyName = $true)]
    [string]$ByUserID,

    [Alias('email')]
    [Parameter(Mandatory=$false,
      HelpMessage = 'Email of the user',
      ValueFromPipelineByPropertyName = $true)]
    [string]$ByUserEmail,

    [Parameter(Mandatory = $false)]
    [switch]
    $SaveCommand,

    [Parameter(Mandatory=$false,
      HelpMessage = 'Pipeline handler',
      ValueFromPipeline = $true,
      ValueFromRemainingArguments = $true,
      DontShow = $true)]
    [pscustomobject]$InputObject
    )

  Begin {
    # Use Max Page Size to reduce the number of requests
    $limit = 1000
    $ApiVersion = '2.1'
    $ApiEndpoint = [System.Text.StringBuilder]'users'

    $Parameters = @()
    $Parameters += ("limit={0}" -f $limit)

    if ($Filter) {
      # An Agent filter was specified
      $Parameters += $Filter.keys | & { process {
        "$_={0}" -f $(if ($Filter.$_.GetType() -eq [Object[]]) {Join-String -Separator "," -InputObject $Filter.$_} else {$Filter.$_})
      }}
    }

    $ParamString = $Parameters -join '&'

    $null = $ApiEndpoint.Append("?")
    $null = $ApiEndpoint.Append($ParamString)
    $ApiEndpoint = $ApiEndpoint.ToString()

    if ($ManagementUrl) {
      $functionParameters += @{
        ManagementUrl = $ManagementUrl
      }
    }

    if ($Credential) {
      $functionParameters += @{
        Credential = $Credential
      }
    }
  }

  Process {

    if ($ByUserID) { # Specific
      $ApiEndpoint = $ApiEndpoint -replace '(\?|\&)ids=', '$1userIds='
      $ApiEndpoint = [pscustomobject]@{GetByUserId = $ByUserID} | Get-S1Filter -ApiEndpoint $ApiEndpoint
    } elseif ($ByUserEmail) { # Specific
      $ApiEndpoint = [pscustomobject]@{GetByUserEmail = $ByUserEmail} | Get-S1Filter -ApiEndpoint $ApiEndpoint
    } elseif ($InputObject) { # Generic
      if ($InputObject.GetType() -eq [int]) { # Strings parsed through pipeline, assume they are names
        $ApiEndpoint = [pscustomobject]@{GetByUserId = $InputObject} | Get-S1Filter -ApiEndpoint $ApiEndpoint
      } else {
        $ApiEndpoint = Get-S1Filter -ApiEndpoint $ApiEndpoint -InputObject $InputObject
      }
    }

    $ApiEndpoint = $ApiEndpoint -replace 'userIds', 'ids'

    # Build
    $functionParameters += @{
      ApiEndpoint = $ApiEndpoint
      ApiVersion  = $ApiVersion
    }

    # Save the command
    if ($SaveCommand) {
      $ApiEndpoint = $ApiEndpoint -replace '(\?|\&)ids=', '$1userIds='
      $params += [pscustomobject]@{ApiEndpoint = $ApiEndpoint} | Get-S1CommandParameter -Invocation $MyInvocation
      return
    }

    # Error checking is all done in the following function so no extra error checking needs to be done.
    # Calling the function and returning the results instantly helps for better pipeline processing
    Invoke-SentinelOneApiRequest @functionParameters | & { process {
      $data = $_
      $result = $_ | Select-Object -Property *,'userId','roleId','accountId','siteId'
      $result.userId = $_.id
      $result.roleId = $_.scopeRoles[0].roleId
      switch ($_.scope) {
        'account' { $result.accountId = $data.scopeRoles[0].id }
        'site' { $result.siteId = $data.scopeRoles[0].id }
      }
      return $result
    }}
  }

  End {
    if ($SaveCommand) {
      Get-S1Command -Command $MyInvocation.MyCommand.Name -Parameters $params
    }
  }
}

function New-SentinelOneConfig {
  [CmdletBinding(SupportsShouldProcess = $true)]
  param(
    [Parameter(Mandatory=$true,
      HelpMessage = 'The base URL for the customers SentinelOne environment')]
    [System.UriBuilder] $ManagementUrl,

    [Parameter(Mandatory=$true,
      HelpMessage = 'The Api Version to use')]
    [float] $ApiVersion,

    [Parameter(Mandatory=$true,
      HelpMessage = 'PSCredential Object containing the API Key in the Password field')]
    [pscredential] $Credential,

    [Parameter(Mandatory=$false,
      HelpMessage = 'Local app data folder name')]
    [string] $ConfigFolderName,

    [Parameter(Mandatory=$false,
      HelpMessage = 'XML config file name')]
    [string] $ConfigFileName
  )

  Begin {
    Write-Verbose "Creating config file"

    if (!$PSBoundParameters.ContainsKey('ConfigFolderName')) {
      $ConfigFolderName = "SentinelOne.Tools"
    }

    if (!$PSBoundParameters.ContainsKey('ConfigFileName')) {
      $ConfigFileName = "SentinelOne.Tools.xml"
    }

    # Define variables
    $configFileFolder = [io.path]::combine($ENV:LOCALAPPDATA, $ConfigFolderName)
    $configFile = [io.path]::combine($configFileFolder, $ConfigFileName)

    Write-Debug ("Received input:
    ManagementUrl: {0}
    ApiVersion: {1}
    Credential: {2}"
 -f $ManagementUrl, $ApiVersion, $Credential)

    Write-Verbose ("Config file location: {0}" -f $configFile)
    # Check if folder / config file exists
    if (!(Test-Path -Path $configFileFolder)) {
      # Folder does not exist
      Write-Verbose ("Config folder does not exist. Creating: {0}" -f $configFileFolder)
      if ($PSCmdlet.ShouldProcess((Split-Path -Parent -Path $configFileFolder), ("Creating folder '{0}'" -f (Split-Path -Leaf -Path $configFileFolder)))) {
        New-Item -Path $configFileFolder -ItemType Directory -Force | Out-Null
      } else {
        # Don't do anything
      }
    }
  }

  Process {

    $config = [pscustomobject]@{
      managementUrl = $ManagementUrl.Host
      apiVersion = $ApiVersion
      credential = $Credential
    }

    Write-Debug ("Config compiled: {0}" -f $config)

    # Create the config file
    if ($PSCmdlet.ShouldProcess((Split-Path -Parent -Path $configFile), ("Creating config file '{0}'" -f (Split-Path -Leaf -Path $configFile)))) {
      $config | Export-Clixml -Path $configFile -Force | Out-Null
    } else {
      # Don't do anything
    }

    Write-Verbose ("Config saved: {0}" -f $configFile)
  }

  End {
    $config = $null
    Remove-Variable -Name config
  }
}

Export-ModuleMember -Function Get-S1Activity, Get-S1ActivityTypes, Get-S1Agent, Get-S1AgentCount, Invoke-SentinelOneApiRequest, Get-S1Group, New-SentinelOneConfig, Get-S1Site, Get-S1Threat, Get-S1User, New-SentinelOneConfig