Powershell API Access

Powershell API Access

$credentials = @{
    "username" = "x"
    "password" = "x"
    "url"      = "x"
}

function Get-FreshService {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        $User,
        [Parameter(Mandatory)]
        $Endpoint,
        [Parameter(Mandatory)]
        [ValidateSet("GET", "POST", "PUT", "DELETE")]
        $Method,
        $Body
    )
    $base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $User.username, $User.password)))

    $Params = @{
        "Uri"         = $User.url + $Endpoint
        "Method"      = $Method
        "ContentType" = "application/json"
        "Headers"     = @{Authorization = ("Basic {0}" -f $base64AuthInfo) }
    }

    switch ($method) {
        "GET" { 
            Invoke-WebRequest @Params #| ConvertFrom-Json
        }
        "POST" {
            Invoke-WebRequest @Params -Body $Body
        }
        "PUT" {}
        "DELETE" {}
        Default {}
    }
}


$data = @()
$data.count
$list = Get-FreshService -User $credentials-Method GET -Endpoint "tickets?include=stats&per_page=100"
($list | ConvertFrom-Json).tickets | % {
    $data += $_
}
$hasmore = $list.RelationLink.ContainsKey("next")

if ($hasmore) {
    $nextpage = $list.RelationLink.Next.Split("/")[-1]
    while ($hasmore -eq $true) {
        $nextpage
        $pages = Get-FreshService -User $credentials -Method GET -Endpoint $nextpage
        ($pages | ConvertFrom-Json).tickets | % {
            $data += $_
        }
        $hasmore = $pages.RelationLink.ContainsKey("next")
        if ($hasmore) {
            $nextpage = $pages.RelationLink.Next.Split("/")[-1]
            #$nextpage
        }
        
    }
}

Function Set-Date {
    Param(
        [Parameter(ValueFromPipeline)]
        $date
    )
    if ($date -ne $null) {
        ($date).ToString('dd-MM-yyyy')
    }
}


$x = ($data).stats | % {
    [PSCustomObject]@{
        Created  = $_.created_at | Set-Date
        Closed   = $_.closed_at | Set-Date
        Resolved = $_.resolved_at | Set-Date
    }
}


Function Calc-Tickets {
    Param($date, $prop)
    ($x | Where-Object { $_."$prop" -eq $date }).Count
}

$month = "12"
$year = "2022"
$ld = [DateTime]::DaysInMonth($year, $month)


1..$ld | % {
    $setdate = (Get-Date -Year $year -Month $month -Day $_).ToShortDateString()
    [PSCustomObject]@{
        Date     = $setdate
        Created  = Calc-Tickets -prop "Created" -date $setdate
        Resolved = Calc-Tickets -prop "Resolved" -date $setdate
        Closed   = Calc-Tickets -prop "Closed" -date $setdate
    }
}

[PSCustomObject]@{
    Open  = ($data | Where-Object {$_.status -eq '2'}).count
    Pending = ($data | Where-Object {$_.status -eq '3'}).count
    Resolved = ($data | Where-Object {$_.status -eq '4'}).count
    Closed   = ($data | Where-Object {$_.status -eq '5'}).count
    Total     = ($data).count
} | FT

 

Ronni Hartung

Lukket for kommentarer.