Public/Get-RemedyKnownError.ps1

Function Get-RemedyKnownError {
<#
.SYNOPSIS
    Retrieves BMC Remedy Known Error details via the API by ID number or other specified criteria such as Assignee, Customer, Team.
 
.DESCRIPTION
    This cmdlet queries the Remedy API for Known Errors as specified by ID number or by combining one or more of the filter parameters.
    Beware that the Remedy API will return a maximum of 5000 incidents in a single request. If you need to exceed this, make multiple
    requests (e.g by separating by date range) and then combine the results.
 
.EXAMPLE
    Get-RemedyKnownError -ID 1234567
 
    Returns the specified Known Error.
.EXAMPLE
    Get-RemedyKnownError -Status Open -Team Windows
 
    Returns all open Known Error records for the specified team.
 
.EXAMPLE
    Get-RemedyKnownError -Status Open -Customer 'Contoso'
 
    Returns all open Known Error records for the specified customer.
 
.EXAMPLE
    Get-RemedyKnownError -Status Open -Team Windows -Customer 'Fabrikam'
 
    Returns all open Known Error records for the specified customer where assigned to the specified team.
.EXAMPLE
    Get-RemedyKnownError -Team Windows -After 01/15/2019 -Before 02/15/2019
 
    Returns all open Known Error records for the specified team between the specified dates.
#>

    [cmdletbinding()]
    Param(
        # One or more Known Error ID numbers.
        [Parameter(Position=0,ValueFromPipeline,ValueFromPipelineByPropertyName)]
        [String[]]$ID = '',
        
        # Known Errors assigned to the specified team.
        [String]$Team,
        
        # Known Errors raised by the specified customer.
        [String]$Customer,
        
        # Known Errors raised for a specific configuration item, e.g a server or other device.
        [Alias('CI')]
        [String]$ConfigurationItem,
        
        # Known Errors assigned to the specified individual.
        [String[]]$Assignee,

        # Known Errors submitted by the specified individual.
        [String[]]$Submitter,

        # Known Errors filtered by specified status. You can also specific 'AllOpen' or 'AllClosed': AllOpen = ('Assigned','Scheduled For Correction','Assigned To Vendor','No Action Planned','Corrected'); AllClosed = ('Closed','Cancelled')
        [ValidateSet('AllOpen','AllClosed','Assigned','Scheduled For Correction','Assigned To Vendor','No Action Planned','Corrected','Closed','Cancelled','')] 
        [String]$Status,
        
        # Include Known Errors of one or more specific types: Normal, Standard, Expedited.
        [ValidateSet('Incident','Change','Problem Investigation','Known Error','Knowledge','Task','CI Unavailability','Purchase Requisition','Release','Activity','')]
        [String[]]$Type,

        # Exclude Known Errors of one or more specific types: Normal, Standard, Expedited.
        [ValidateSet('Incident','Change','Problem Investigation','Known Error','Knowledge','Task','CI Unavailability','Purchase Requisition','Release','Activity','')]
        [String[]]$ExcludeType,

        # Include Known Errors of one or more specific priorities: Low, Medium, High, Critical.
        [ValidateSet('Low','Medium','High','Critical','')]
        [String[]]$Priority = '',
        
        # Known Errors with a 'submit date' that is after this date. Use US date format: mm/dd/yyyy
        [DateTime]$After,
        
        # Known Errors with a 'submit date' that is before this date. Use US date format: mm/dd/yyyy
        [DateTime]$Before,

        # Return all available data fields from Remedy.
        [Switch]$Full,

        # Match the string exactly.
        [Switch]$Exact,

        # An encoded string representing your Remedy Credentials as generated by the Set-RemedyApiConfig cmdlet.
        [String]$EncodedCredentials = (Get-RemedyApiConfig).Credentials,

        # The Remedy API URL. E.g: https://<localhost>:<port>/api
        [String]$APIURL = (Get-RemedyApiConfig).APIURL
    )
    
    If (-not $EncodedCredentials -or -not $APIURL) { Throw 'Remedy API Config not set. Set-RemedyApiConfig first.' }
    
    If (-not (Test-RemedyApiConfig)) { Throw 'Remedy API Test failed. Ensure the config has been set correctly via Set-RemedyApiConfig.' }

    Switch ($Status) {
        'AllOpen'   { $Filter = 'Assigned','Scheduled For Correction','Assigned To Vendor','No Action Planned','Corrected' }
        'AllClosed' { $Filter = 'Closed','Cancelled' }
        Default     { $Filter = $Status }  
    }
    
    If ($Filter) { $StatusString = ($Filter | ForEach-Object { "('Known Error Status'=""$_"")" }) -join 'OR' }
    If ($Type)           { $TypeString = ($Type | ForEach-Object { "('TicketType'=""$_"")" }) -join 'OR' }
    If ($ExcludeType)    { $ExcludeTypeString = ($ExcludeType | ForEach-Object { "('TicketType'!=""$_"")" }) -join 'AND' }
    
    If ($Priority) { $PriorityString = ($Priority | ForEach-Object { "('Priority'=""$_"")" }) -join 'OR' }
     
    ForEach ($IDNum in $ID) {
        Write-Verbose "$IDNum"
        
        $Filter = @()
        
        If ($Exact) { $Op = '='; $Wc = '' } Else { $Op = 'LIKE'; $Wc = '%25' }
        If ($Exact -or $IDNum -match '^PKE\d{12}') { $IDOp = '='; $IDWc = '' } Else { $IDOp = 'LIKE'; $IDWc = '%25' }
        
        If ($IDNum)    { $Filter += "'Known Error ID'$IDOp""$IDWc$IDNum""" }
        If ($Team)     { $Filter += "'Assigned Group'=""$Team""" }
        If ($Customer) { $Filter += "'Company'$Op""$Wc$Customer$Wc""" }
        If ($ConfigurationItem) { $Filter += "'PKE_CI'$Op""$Wc$ConfigurationItem$Wc""" }
        
        If ($Assignee -is [Array]) { 
            $AssigneeString = ($Assignee | ForEach-Object { "('Assignee'$Op""$Wc$_$Wc"")" }) -join 'OR'
            $Filter += "($AssigneeString)"
        } ElseIf ($Assignee -is [String]) {
             $Filter += "'Assignee'$Op""$Wc$Assignee$Wc""" 
        }
        
        If ($Submitter -is [Array]) { 
            $SubmitterString = ($Submitter | ForEach-Object { "('Submitter'$Op""$Wc$_$Wc"")" }) -join 'OR'
            $Filter += "($SubmitterString)"
        } ElseIf ($Submitter -is [String]) {
             $Filter += "'Submitter'$Op""$Wc$Submitter$Wc""" 
        }
         
        If ($Type)          { $Filter += "($TypeString)" }
        If ($ExcludeType)   { $Filter += "($ExcludeTypeString)" }
        
        If ($Priority)      { $Filter += "($PriorityString)" }
        
        If ($After)  { $Filter += "'Submit Date'>""$($After.ToString("yyyy-MM-dd"))""" }
        If ($Before) { $Filter += "'Submit Date'<""$($Before.ToString("yyyy-MM-dd"))""" }

        If ($StatusString) { $Filter += "($StatusString)" }
        $FilterString = $Filter -Join 'AND'

        $Headers = @{
            Authorization = "Basic $EncodedCredentials"
        }

        If (-not $FilterString) { Throw 'Please provide at least one search criteria. Enter Help Get-RemedyKnownError for further guidance.' }

        $URL = "$APIURL/PBM:Known Error/$FilterString"
    
    
        Try {
            $Result = Invoke-RestMethod -URI $URL -Headers $Headers -ErrorAction Stop
            
            $KnownErrors = @()
            $Result.PSObject.Properties | ForEach-Object { $KnownErrors += $_.Value }
            
            #Convert all date containing fields to PS datetime
            ForEach ($KnownError in $KnownErrors) { 
                
                $KnownError.PSObject.Properties.Name -like '* Date*' | ForEach-Object {
                        
                    If ($KnownError.$_ -match 'UTC'){
                        $KnownError.$_ = [datetime]::ParseExact(($KnownError.$_ -Replace 'UTC ',''), 'ddd MMM dd HH:mm:ss yyyy', $null)
                    }
                }
            }
                                
            #Could replace this with a format.ps1.xml
            If (-not $Full){
                $KnownErrors = $KnownErrors |  Select-Object 'Known Error ID','Priority','Company',
                                                       'Description',@{N='Status';E={$_.'Known Error Status'}},'Assigned Group','Assignee',
                                                       @{N='CI';E={$_.PKE_CI}},'Submit Date','Last Modified Date','Last Modified By'
            }
        } Catch {
            
            Write-Error "Error: $_"
        }

        If ($null -ne $KnownErrors.'Known Error ID') {
            $KnownErrors.psobject.TypeNames.Insert(0, 'RemedyKnownError')
            $KnownErrors
        } Else {
            Write-Verbose 'No KnownError data returned'
        }
    }
}