PSGrafana.psm1

function Get-GrafanaAlert {
    <#
    .SYNOPSIS
    Query Grafana API for alert information
     
    .PARAMETER DashboardId
    The ID of the dashboard to query
     
    .PARAMETER DashboardName
    The friendly name of the dashboard to query
     
    .PARAMETER DashboardTag
    Search for alerts belong to a dashboard with a specific tag
     
    .PARAMETER AlertName
    Query for all alerts matching the alert name
     
    .PARAMETER State
    Query for all alerts in the state of 'ALL','no_data','paused', 'alerting','ok','pending'
     
    .EXAMPLE
    Get-GrafanaAlert
 
    .EXAMPLE
    Get-GranaAlert -DashboardId 1
 
    .EXAMPLE
    Get-GrafanaAlert -DashboardName "PeterRabbit"
 
    .EXAMPLE
    Get-GrafanaAlert -DashboardTag 'prod'
 
    .EXAMPLE
    Get-GrafanaAlert -AlertName 'Perrywinkle'
 
    .EXAMPLE State
    Get-GrafanaAlert -State 'paused'
 
    #>

    
    [cmdletBinding(HelpUri="https://github.com/steviecoaster/PSGrafana/wiki/Get-GrafanaAlert")]
    Param(
        
        [Parameter()]
        [Int[]]
        $DashboardId,

        [Parameter()]
        [String]
        $DashboardName,

        [Parameter()]
        [String[]]
        $DashboardTag,

        [Parameter()]
        [Alias('Query')]
        [String]
        $AlertName,

        [Parameter()]
        [String[]]
        [ValidateSet('ALL','no_data','paused', 'alerting','ok','pending')]
        $State
    )

    begin { $null = Get-GrafanaConfig } 

    process { 
        
        $irmParams = @{
            headers = @{ Authorization = "Bearer $($Configuration.apikey)"}
            Method      = "GET"
            ContentType = "application/json"
        }

        If($PSBoundParameters.Count -eq 0){

            $irmParams.Add("Uri","$($configuration.GrafanaUri)/alerts")
        }

        Else {

            Switch($PSBoundParameters.Keys){ 

                "DashboardName" {

                    $irmParams.Add("Uri","$($configuration.GrafanaUri)/alerts?dashboardQuery=$Dashboardname")

                }

                "DashboardId" { 
                    
                    $url = "$($configuration.GrafanaUri)/alerts?"
                    foreach ($id in $DashboardId) {
                        $url += "dashboardId={0}&" -f $id
                    }
                    $irmParams.Add("Uri","$($url -replace ".$")")
                
                }

                "DashboardTag" {

                    $url = "$($configuration.GrafanaUri)/alerts?"
                    foreach ($id in $DashboardTag) {
                        $url += "dashboardTag={0}&" -f $id
                    }
                    $irmParams.Add("Uri","$($url -replace ".$")")

                }

                "State" {
                    
                    $url = "$($configuration.GrafanaUri)/alerts?"
                    foreach ($id in $State) {
                        $url += "state={0}&" -f $id
                    }
                    $irmParams.Add("Uri","$($url -replace ".$")")

                }

                "Alertname" { 

                    $irmParams.Add("Uri","$($configuration.GrafanaUri)/alerts?query=$AlertName")

                }
                
            }#switch
        
        }#else

        $irmParams['Uri']
        $result = Invoke-RestMethod @irmParams

        $result

    }#process

}
function Get-GrafanaAnnotation {
    <#
    .SYNOPSIS
    Retrieves annotations via the Grafana API
     
    .DESCRIPTION
    Search for various types of annotations via the Grafana API
     
    .PARAMETER From
    The start time to search
     
    .PARAMETER To
    The end time to search
     
    .PARAMETER AlertName
    The specific alert annotation you want to find
     
    .PARAMETER DashboardName
    The specific dashboard to return results for
     
    .PARAMETER PanelName
    The specific panel to retrieve results for
     
    .PARAMETER Username
    The specific username to search for
     
    .PARAMETER Type
    Retrieve annotations of a certain type
     
    .PARAMETER Tags
    Retrieve annotation based on tags
     
    .PARAMETER All
    Return all annotations
     
    .PARAMETER Credential
    The Grafana credentials to use to retrieve annotations
     
    .EXAMPLE
    Get-GrafanaAnnotation -All -Credential $cred
 
    .EXAMPLE
    Get-GrafanaAnnotation -DashboardName WebServer
 
    .EXAMPLE
    Get-GrafanaAnnotation -Username bob
     
    #>

    
    [cmdletBinding(HelpUri="https://github.com/steviecoaster/PSGrafana/wiki/Get-GrafanaAnnotation")]
    Param(
        [Parameter(Mandatory,Position=0,ParameterSetName="time")]
        [String]
        $From,

        [Parameter(Mandatory,Position=1,ParameterSetName="time")]
        [string]
        $To,

        [Parameter(Mandatory,Position=0,ParameterSetName="alert")]
        [String]
        $AlertName,

        [Parameter(Mandatory,Position=0,ParameterSetName="dashboard")]
        [String]
        $DashboardName,

        [Parameter(Mandatory,Position=0,ParameterSetName="panel")]
        [String]
        $PanelName,

        [Parameter(Mandatory,Position=0,ParameterSetName="user")]
        [String]
        $Username,

        [Parameter(Mandatory,Position=0,ParameterSetName="type")]
        [ValidateSet("Alert","Annotation")]
        [String]
        $Type,

        [Parameter(Mandatory,Position=0,ParameterSetName="tags")]
        [String[]]
        $Tags,

        [Parameter(Mandatory,Position=0,ParameterSetName="all")]
        [Switch]
        $All,

        [Parameter(Mandatory,Position=1,ParameterSetName="all")]
        [Parameter(Mandatory,Position=2,ParameterSetName="time")]
        [Parameter(Mandatory,Position=1,ParameterSetName="alert")]
        [Parameter(Mandatory,Position=1,ParameterSetName="dashboard")]
        [Parameter(Mandatory,Position=1,ParameterSetName="panel")]
        [Parameter(Mandatory,Position=1,ParameterSetName="user")]
        [Parameter(Mandatory,Position=1,ParameterSetName="type")]
        [Parameter(Mandatory,Position=1,ParameterSetName="tags")]
        [PSCredential]
        $Credential

    )
    
    begin { $null = Get-GrafanaConfig }

    process {

        $irmParams = @{
            
            Method      = "GET"
            ContentType = "application/json"
            Authentication = "Basic"
            Credential = $Credential

        }

        If($($configuration.GrafanaUri) -match '^(http://)'){
                    
            $irmParams.Add('AllowUnencryptedAuthentication',$true)
        
        }
    

        Switch($PSCmdlet.ParameterSetName){

            'time' {}
            'alert' {

                $alertId = Get-GrafanaAlert | Where-Object { $_.Name -eq "$AlertName" } | Select -ExpandProperty id

                $irmParams.Add('Uri',"$($configuration.GrafanaUri)/annotations?alertId=$alertID")

            }
            'dashboard' {

                $dashboardId = Get-GrafanaDashboard | Where-Object { $_.title -eq "$DashboardName"} | Select-Object -ExpandProperty id

                $irmParams.Add('Uri',"$($configuration.GrafanaUri)/annotations?dashboardId=$dashboardId")

            }
            'panel' {}
            'user' {

                $userId = Get-GrafanaUser -Username $Username | Select-Object -ExpandProperty id

                $irmParams.Add('Uri',"$($configuration.GrafanaUri)/annotations?userId=$userId")

            }
            'type' {

                $irmParams.Add('Uri',"$($configuration.GrafanaUri)/annotations?type=$($Type.ToLower())")

            }
            'tags' {

                $uri = @("$($configuration.GrafanaUri)/annotations?tags=")
                
                $tags = $Tags -join "&tags="

                Write-Host $uri$tags

                $irmParams.Add('Uri',"$uri$tags")


            }

            'all' {

                $irmParams.Add('Uri',"$($configuration.GrafanaUri)/annotations")

            }
        }

        $result = Invoke-RestMethod @irmParams

        $result

    }

}
function Get-GrafanaApiKey {
    <#
        .SYNOPSIS
        Retrieve a list of API keys created in Grafana
 
        .EXAMPLE
        Get-GrafanaApiKey
    #>

    [cmdletBinding(HelpUri="ttps://github.com/steviecoaster/PSGrafana/wiki/Get-GrafanaApiKey")]
    Param()
    
    begin { $null = Get-GrafanaConfig }

    process {
        
        $header = @{ Authorization = "Bearer $($Configuration.apikey)"}

        $irmParams = @{
            Method = 'GET'
            Uri = "$($Configuration.GrafanaUri)/auth/keys"
            Headers = $header
            ContentType = "application/json"

        }

        Invoke-RestMethod @irmParams
    }
}
function Get-GrafanaConfig {
    <#
        .SYNOPSIS
        Reads the Grafana.json file and returns an object
         
        .PARAMETER ConfigurationFile
        The path to the configuration json. Defaults to Config\Grafana.json
         
        .EXAMPLE
        Get-GrafanaConfig
         
        .EXAMPLE
        Get-GrafanaConfig -ConfigurationFile C:\Configs\Grafana.json
         
    #>

    [CmdletBinding(HelpUri="https://github.com/steviecoaster/PSGrafana/wiki/Get-GrafanaConfig")]
    Param(
        [Parameter(Position=0)]
        [String]

        $ConfigurationFile = "$PSScriptRoot\Config\Grafana.json"

    )

    begin {}

    process {
        
        $Global:Configuration = Get-Content $ConfigurationFile | ConvertFrom-Json 

        $Configuration
    
    }

    end {}

}
function Get-GrafanaDashboard {
    <#
        .SYNOPSIS
        Returns an object with details about a Grafana dashboard
         
        .PARAMETER Name
        Search the Grafana instance for dashboards by friendly name
         
        .PARAMETER Uuid
        Search the Grafana instance for dashboards by UID
         
        .PARAMETER Tag
        Search the Grafana instance for dashboards by Tag
         
        .PARAMETER IncludeMetadata
        Include extra metadata about the dashboard. Excluded by default.
         
        .EXAMPLE
        Get-GrafanaDashboard -Name 'Prod - FileServer'
         
        .EXAMPLE
        Get-GrafanaDashboard -Uuid O0E3f5t
         
        .EXAMPLE
        Get-GrafanaDashboard -Name 'Smiley' -IncudeMetadata
     
    #>

    [cmdletBinding(HelpUri="https://github.com/steviecoaster/PSGrafana/wiki/Get-GrafanaDashboard",DefaultParameterSetName="All")]
    Param(

        [Parameter(Position=0,ParameterSetName='All')]
        [Switch]
        $All,

        [Parameter(Position=0,ParameterSetName='Name')]
        [String]
        $Name,

        [Parameter(Position=0,ParameterSetName='Uuid')]
        [String]
        $Uuid,

        [Parameter(Position=0,ParameterSetName='Tag')]
        [String]
        $Tag,

        [Parameter()]
        [Switch]
        $IncludeMetadata
    )

    begin { $null = Get-GrafanaConfig }

    process {

        $header = @{ Authorization = "Bearer $($Configuration.apikey)"}

        Switch($PSCmdlet.ParameterSetName){

            'Name' {
                
                $irmParams = @{
            
                    Method      = "GET"
                    Uri         = "$($configuration.GrafanaUri)/search?query=$Name"
                    Headers     = $header
                    ContentType = "application/json"

                }

                $result = Invoke-RestMethod @irmParams

                $result
            
            }

            'Uuid' {
                
                $irmParams = @{
            
                    Method      = "GET"
                    Uri         = "$($configuration.GrafanaUri)/dashboards/uid/$uuid" 
                    Headers     = $header
                    ContentType = "application/json"
    
                }

                $result = Invoke-RestMethod @irmParams
                
                If($IncludeMetadata){
            
                    $result | Format-List
        
                }
        
                Else { 
        
                    $result.dashboard
                }
            
            }

            'Tag' {
                
                $irmParams = @{
            
                    Method      = "GET"
                    Uri         =  "$($configuration.GrafanaUri)/search?tag=$Tag" 
                    Headers     = $header
                    ContentType = "application/json"
    
                }

                $result = Invoke-RestMethod @irmParams
                
                $result.Content | ConvertFrom-Json
            
            }

            'All' {

                $irmParams = @{
            
                    Method      = "GET"
                    Uri         =  "$($configuration.GrafanaUri)/search?type=dash-db" 
                    Headers     = $header
                    ContentType = "application/json"
    
                }

                $result = Invoke-RestMethod @irmParams

                $result

            }

        
        }#switch

        
    }#process

}#function
function Get-GrafanaDatasource {
    <#
    .SYNOPSIS
    Fetch information about Grafana datasources via the API
     
    .PARAMETER All
    Returns all datasources in your Grafana Instance
     
    .PARAMETER DatasourceId
    The ID of the datasource for which to search
     
    .PARAMETER DatasourceName
    The friendly name of the datasource for which to search
     
    .EXAMPLE
    Get-GrafanaDatasource -All
 
    .EXAMPLE
    Get-GrafanaDatasource -DatasourceId 4
 
    .EXAMPLE
    Get-GrafanaDatasource -Datasourcename ElasticPuppies
     
    .NOTES
     
    #>

    
    [cmdletBinding(HelpUri="https://github.com/steviecoaster/PSGrafana/wiki/Get-GrafanaDatasource")]
    Param(
        [Parameter()]
        [Switch]
        $All,

        [Parameter()]
        [Int]
        $DatasourceId,

        [Parameter()]
        [String]
        $DatasourceName

    )

    begin { $null = Get-GrafanaConfig }

    process {

        $header = @{ Authorization = "Bearer $($Configuration.apikey)"}

        If($All){

            $irmParams = @{
            
                Method      = "GET"
                Uri         = "$($configuration.GrafanaUri)/datasources" 
                Headers     = $header
                ContentType = "application/json"

            }

            $result = Invoke-RestMethod @irmParams

            $result
        }

        Switch($PSBoundParameters.Keys){

            'DatasourceId' {
                $irmParams = @{
            
                    Method      = "GET"
                    Uri         = "$($configuration.GrafanaUri)/datasources/$DatasourceId" 
                    Headers     = $header
                    ContentType = "application/json"
    
                }
    
                $result = Invoke-RestMethod @irmParams
    
                $result
            }

            'DatasourceName' {
                $irmParams = @{
            
                    Method      = "GET"
                    Uri         = "$($configuration.GrafanaUri)/datasources/name/$DatasourceName" 
                    Headers     = $header
                    ContentType = "application/json"
    
                }
    
                $result = Invoke-RestMethod @irmParams
    
                $result

            }
        }

    }
}
function Get-GrafanaFolder {
    <#
    .SYNOPSIS
    Retrieve folder information from Grafana via the API
     
    .DESCRIPTION
    You can search for Grafana folders via the API with this cmdlet. You may search via Uid,Id, or return All folders
     
    .PARAMETER Uid
    The UID value of a folder you wish to search for. This is an alphanumeric value
     
    .PARAMETER Id
    This is the ID of the folder you wish to search for. This is an int value
     
    .PARAMETER All
    Return all folders which you have access too.
     
    .EXAMPLE
    Get-GrafanaFolder
 
    Returns all folders which the user has access to in Grafana.
     
    .EXAMPLE
    Get-GrafanaFolder -Uid Ax8x33
 
    Returns the information for the folder with the Uid you entered
 
    .EXAMPLE
    Get-GrafanaFolder -Id 3
 
    Returns the information for the folder with the specified ID
    
    #>


    [cmdletBinding(HelpUri="hhttps://github.com/steviecoaster/PSGrafana/wiki/Get-GrafanaFolder",DefaultParameterSetName="All")]
    Param(
        [Parameter(ParameterSetName="Uid")]
        [String]
        $Uid,

        [Parameter(ParameterSetName="Id")]
        [Int]
        $Id,

        [Parameter(ParameterSetName="All")]
        [Switch]
        $All

    )

    begin { $null = Get-GrafanaConfig }
    
    process {

        $irmParams = @{
            
            Method      = "GET"
            Headers     = @{ Authorization = "Bearer $($Configuration.apikey)"}
            ContentType = "application/json"

        }

        Switch ($PSCmdlet.ParameterSetName) {

            'Uid' {

                $irmParams.Add('Uri',"$($configuration.GrafanaUri)/folders/$Uid")

            }

            'Id' {
            
                $irmParams.Add('Uri',"$($configuration.GrafanaUri)/folders/id/$Id")
            
            }
            
            default {

                $irmParams.Add('Uri',"$($configuration.GrafanaUri)/folders")

            }
        }

        $return = Invoke-RestMethod @irmParams

        $return
        
    }
}
function Get-GrafanaOrg {
    <#
    .SYNOPSIS
    Returns information about Grafana Organizations
     
    .DESCRIPTION
    Returns information about various organizations configured in your Grafana installation.
     
    .PARAMETER OrgName
    Specify an Org name to retrieve information about that Org
     
    .PARAMETER CurrentOrg
    Retrieve information about the Current Org the user belongs too.
     
    .EXAMPLE
    Get-GrafanaOrg -OrgName Headquarters
 
    .EXAMPLE
    Get-GrafanaOrg -CurrentOrg
  
    #>

    
    [cmdletBinding(HelpUri="https://github.com/steviecoaster/PSGrafana/wiki/Get-GrafanaOrg")]
    Param(
        [Parameter()]
        [String]
        $OrgName,

        [Parameter()]
        [Switch]
        $CurrentOrg
    )

    begin { $null = Get-GrafanaConfig } 

    process {
        
        $irmParams = @{
            
            Method = 'GET'
            Headers = @{ Authorization = "Bearer $($Configuration.apikey)"}
            ContentType = "application/json"

        }

        Switch($PSBoundParameters.Keys){

            'OrgName' {

                $irmParams.Add('Uri',"$($configuration.GrafanaUri)/orgs/name/$OrgName")

            }

            'CurrentOrg' {

                $irmParams.Add('Uri',"$($configuration.GrafanaUri)/org")
                
            }

        }

        $return = Invoke-RestMethod @irmParams

        $return

    }
}
function Get-GrafanaOrgUser {
    <#
    .SYNOPSIS
    Returns all users within the current org
     
    .DESCRIPTION
    Returns all users of the current org in the context of the API key token holder's context
     
    .EXAMPLE
    Get-GrafanaOrgUser
    
    #>

    
    [cmdletBinding(HelpUri="https://github.com/steviecoaster/PSGrafana/wiki/Get-GrafanaOrgUser")]
    Param(
        
    )

    begin { $null = Get-GrafanaConfig } 

    process {
        
        $irmParams = @{
            
            Method      = 'GET'
            Headers     = @{ Authorization = "Bearer $($Configuration.apikey)"}
            ContentType = "application/json"
            Uri         ="$($configuration.GrafanaUri)/org/users"

        }

        $return = Invoke-RestMethod @irmParams

        $return

    }
}
function Get-GrafanaServerHealth {
    <#
         
        .SYNOPSIS
        Returns Grafana server health info
 
        .EXAMPLE
 
        Get-GrafanaServerhealth
 
    #>


    [cmdletBinding(HelpUri="https://github.com/steviecoaster/PSGrafana/wiki/Get-GrafanaServerHealth")]
    Param()
    
    begin { $null = Get-GrafanaConfig}

    process {
        
         Invoke-RestMethod -Uri "$($Configuration.GrafanaUri)/health"
    
    }

}
function Get-GrafanaServerSettings { 
    <#
    .SYNOPSIS
    Returns server settings for your Grafana Instance
     
    .DESCRIPTION
    Returns the currently configured settings for your Grafana instance. User must be an Org Admin to retrieve these settings
     
    .PARAMETER Credential
    The credentials you wish to use
     
    .EXAMPLE
    Get-GrafanaServerSettings
     
    #>

    
    [cmdletBinding(HelpUri="https://github.com/steviecoaster/PSGrafana/wiki/Get-GrafanaServerSettings")]
    Param(
        [Parameter(Mandatory,Position=0)]
        [PSCredential]
        $Credential
    )

    begin { $null = Get-GrafanaConfig }

    process {

        $irmParams = @{
            
            Method = 'GET'
            Authentication = "Basic"
            Credential = $Credential
            ContentType = "application/json"
            Uri = "$($configuration.Grafanauri)/admin/settings"
        }

        If($($configuration.GrafanaUri) -match '^(http://)'){
                    
            $irmParams.Add('AllowUnencryptedAuthentication',$true)
        
        }

        $result = Invoke-RestMethod @irmParams

        $result

    }
}
function Get-GrafanaSnapshot { 
    <#
    .SYNOPSIS
    Retrieve Grafana Snapshots via API
     
    .DESCRIPTION
    Retrieve a single snapshot by Name, or return All snapshots
     
    .PARAMETER SnapshotName
    The friendly name of the Snapshot to retrieve
     
    .PARAMETER All
    Switch to return all snapshots
     
    .EXAMPLE
    Get-GrafanaSnapshot -SnapshotName SnappyMcSnapperson
 
    .EXAMPLE
    Get-GrafanaSnapshot -All
     
    #>

    
    [cmdletBinding(DefaultParameterSetName="Snapshot",HelpUri="https://github.com/steviecoaster/PSGrafana/wiki/Get-GrafanaSnapshot")]
    Param(
        [Parameter(Mandatory,ParameterSetName="Snapshot")]
        [String]
        $SnapshotName,

        [Parameter(Mandatory,ParameterSetName="All")]
        [Switch]
        $All
    )

    begin { $null = Get-GrafanaConfig }

    process {
        $irmParams = @{
            
            Method      = "GET"
            Headers     = @{ Authorization = "Bearer $($Configuration.apikey)"}
            ContentType = "application/json"

        }

        Switch($PSCmdlet.ParameterSetName){

            'Snapshot' {
                
                $irmParams.Add("Uri","$($configuration.GrafanaUri)/dashboard/snapshots/?query=$SnapshotName")

            }

            'All' {

                $irmParams.Add("Uri","$($configuration.GrafanaUri)/dashboard/snapshots")

            }
        }
       
        $result = Invoke-RestMethod @irmParams

        $result

    }
}
function Get-GrafanaUser {
   <#
   .SYNOPSIS
   Return information about a Grafana user.
    
   .DESCRIPTION
   Search via Email Address or Username for information about the specified Grafana user.
    
   .PARAMETER Username
   The username to query information for
    
   .PARAMETER Credential
   The credentials to use when searching by username
    
   .PARAMETER EmailAddress
   The email address to query information for
    
   .EXAMPLE
   Get-GrafanaUser -EmailAddress bob@foo.com
 
   .EXAMPLE
   Get-GrafanaUser -Username bob -Credential grafana_admin
 
    You will be prompted to enter the password for grafana_admin
 
    .EXAMPLE
    Get-GrafanaUser -Username bob -Credential (Get-Credential)
 
    Provide the username and password of an org admin in Grafana to the Credential prompt
 
    .EXAMPLE
    Get-GrafanaUser -Username bob -Credential $Credential
 
    Use a stored Grafana org admin credential
    
   .NOTES
   General notes
   #>

       
    [cmdletBinding(HelpUri="https://github.com/steviecoaster/PSGrafana/wiki/Get-GrafanaUser",DefaultParameterSetName="Email")]
    Param(
        
        [Parameter(Mandatory,ParameterSetName="Username")]
        [String]
        $Username,

        [Parameter(Position=0,Mandatory,ParameterSetName="Email")]
        [String]
        $EmailAddress,

        [Parameter(Position=0,Mandatory,ParameterSetName="All")]
        [Switch]
        $All,

        [Parameter(Mandatory,ParameterSetName="All")]
        [Parameter(Mandatory,ParameterSetName="Username")]
        [Parameter(Mandatory,ParameterSetName="Email")]
        [PSCredential]
        $Credential
    )

    begin { $null = Get-GrafanaConfig }

    process {

        $irmParams = @{
            
            Method      = "GET"
            ContentType = "application/json"

        }

        If($($configuration.GrafanaUri) -match '^(http://)'){
                    
            $irmParams.Add('AllowUnencryptedAuthentication',$true)
        
        }

        Switch($PSCmdlet.ParameterSetName){

            'Username' {

                
                    $irmParams.Add('Uri',"$($configuration.GrafanaUri)/users/search?query=$Username")
                    $irmParams.Add('Authentication', "Basic")
                    $irmParams.Add('Credential', $Credential)
            }

            'Email' {

                    $irmParams.Add('Uri',"$($configuration.GrafanaUri)/users/search?query=$EmailAddress")
                    $irmParams.Add('Authentication', "Basic")
                    $irmParams.Add('Credential', $Credential)

            }

            'All' { 

                $irmParams.Add('Uri',"$($configuration.GrafanaUri)/users/search")
                $irmParams.Add('Authentication', "Basic")
                $irmParams.Add('Credential', $Credential)


            }

        }

        $return = Invoke-RestMethod @irmParams

        $output = [System.Collections.Generic.List[pscustomobject]]::new()

        $return.users | ForEach-Object { $output.Add([pscustomobject]$_) }

        $output

    }

}
function New-GrafanaApiKey {
    <#
        .SYNOPSIS
        Creates a new API key in Grafana
         
        .PARAMETER Name
        The friendly name of the API key
         
        .PARAMETER Role
        The access level for the key. Available options are Admin,Editor, and Viewer
         
        .EXAMPLE
        New-GrafanaApiKey -Name RickyBobby -Role Admin
 
        .EXAMPLE
        New-GrafanaApiKey -Name Alice -Role Editor
 
        .NOTES
        The generated API key is only displayed at runtime. If you need to retain it for any reason, be sure to it somewhere safe.
        It is highly recommended you run this command saved to a variable such as $ApiKey = New-GrafanaApiKey -Name ElmerFudd -Role Viewer.
        This way you can access the properties Name and Key within the variable. E.g. $ApiKey.name, or $ApiKey.key.
    #>

    [cmdletBinding(HelpUri="https://github.com/steviecoaster/PSGrafana/wiki/New-GrafanaApiKey")]
    Param(
        
        [Parameter(Mandatory,Position=0)]
        [String]
        $Name,

        [Parameter(Mandatory,Position=1)]
        [ValidateSet('Admin','Viewer','Editor')]
        [String]
        $Role

    )

    begin { 
        
        $null = Get-GrafanaConfig
        
    }

    process {
        
        $header = @{ Authorization = "Bearer $($Configuration.apikey)"}
        $body = @{name = $Name; role = $Role} | ConvertTo-Json

        $irmParams = @{
            Method = 'POST'
            Uri = "$($Configuration.GrafanaUri)/auth/keys"
            Body = "$body"
            Headers = $header
            ContentType = "application/json"

        }
        Write-Warning -Message "You'll only see the API key generated here one time. There is no method to retrieve/generate it."
        Invoke-RestMethod @irmParams

    }

}
function New-GrafanaDashboard {
    <#
    .SYNOPSIS
    Add a new dashboard to Grafana
     
    .DESCRIPTION
    This cmdlet adds a new dashboard to the specified folder inside of Grafana
     
    .PARAMETER Title
    The Title of the Dashbaord
     
    .PARAMETER Tags
    The tags you wish the Dashboard to use
     
    .PARAMETER Folder
    The folder in which to store the Dashboard in Grafana
     
    .EXAMPLE
    New-GrafanaDashboard -Title "My Awesome Dashboard" -Folder "Fancy Dashboards"
 
    .EXAMPLE
    New-GrafanaDashboard -Title "My Awesome Dashboard" -Tags "production","webserver","cats" -Folder Home
     
    #>

    
    [cmdletBinding(DefaultParameterSetName="New")]
    Param(
        [Parameter(Mandatory,ParameterSetName="New")]
        [String]
        $Title,

        [Parameter(ParameterSetName="New")]
        [String[]]
        $Tags,

        [Parameter(Mandatory,ParameterSetName="New")]
        [String]
        $Folder

       
    )

    begin { $null = Get-GrafanaConfig }

    process {

        $irmParams = @{
            Headers = @{ Authorization = "Bearer $($Configuration.apikey)"}
            ContentType = "application/json"
            Method = "POST"
            Uri = "$($configuration.GrafanaUri)/dashboards/db"
        }

        $body = @{}
        $dashboard = @{
            
            title = "$Title"
            tags = $Tags

        }

        $FolderId = Get-GrafanaFolder | Where-Object { $_.title -eq $Folder } | Select-Object -ExpandProperty id
        
        $body.Add('folderId',$FolderId)
        $body.Add("overwrite",$false)
        $body.Add("dashboard",$dashboard)
        
        $dashboard.Add("id",$null)
        $dashboard.Add("uid",$null)       

        $irmParams.Add('Body',($body | ConvertTo-Json))

        $result = Invoke-RestMethod @irmParams

        $result

    }#process

}#function
function New-GrafanaFolder { 
    <#
    .SYNOPSIS
    Create a new folder in Grafana via the API
     
    .DESCRIPTION
    The Grafana API allows you to create new folders. This cmdlet accomplishes this. Title is required, but you may supply an optional Uid.
    If you don't specify a Uid, one will be generated for you by the API at runtime.
     
    .PARAMETER Title
    The title of the folder you wish to create with the API
     
    .PARAMETER Uid
    The uid to give the folder when created by the API
     
    .EXAMPLE
    New-GrafanaFolder -Title "My Awesome Folder"
 
    Creates a new folder in Grafana called "My Awesome Folder"
     
    .EXAMPLE
    New-GrafanaFolder -Title "Web Farm Folder" -Uid nErXDvCkzz
 
    Creates a new folder in Grafana called "Web Farm Folder" with a Uid of nErXDvCkzz
     
    .NOTES
    General notes
    #>

    
    [CmdletBinding(HelpUri="https://github.com/steviecoaster/PSGrafana/wiki/New-GrafanaFolder")]
    Param(
        [Parameter(Mandatory,Position=0)]
        [String]
        $Title,

        [Parameter(Position=1)]
        [String]
        $Uid
    )

    begin { $null = Get-GrafanaConfig }

    process {

        $body = @{

            title = $Title
            
        }
    
        If($Uid){
    
            $body.Add('uid',$Uid)
        }

        $irmParams = @{
            
            Method      = "POST"
            Headers     = @{ Authorization = "Bearer $($Configuration.apikey)"}
            Uri         = "$($Configuration.GrafanaUri)/folders"
            ContentType = "application/json"
            Body = $body | ConvertTo-Json

        }

        Invoke-RestMethod @irmParams

    }
}
function New-GrafanaSnapshot {
    <#
        .SYNOPSIS
        Take a snapshot of a dashboard in Grafana
 
        .PARAMETER DashboardTitle
        Title of the dashboard you wish to snapshot
 
        .PARAMETER SnapshotName
        Name of the snapshot you are creating
 
        .PARAMETER Expires
        Time (in seconds) the snapshot stays alive. Set to 0 to never expire.
     
        .EXAMPLE
        New-GrafanaSnapshot -DashboardTitle WebHosts -SnapshotName WebSnap -Expires 0
         
        Create a new snapshot of WebHosts with the name WebSnap that never expires
    #>


    [cmdletBinding(HelpUri="https://github.com/steviecoaster/PSGrafana/wiki/New-GrafanaSnapshot")]
    Param(

        [Parameter(Mandatory,Position=0)]
        [String]
        $DashboardTitle,

        [Parameter(Mandatory,Position=1)]
        [String]
        $SnapshotName,

        [Parameter(Position=0)]
        [Int]
        $Expires = 0
    )

    begin { $null = Get-GrafanaConfig}
    
    process {
        
        
        $irmParams = @{
            
            headers = @{ Authorization = "Bearer $($Configuration.apikey)"}
            body= @{
            
                dashboard = [ordered]@{
                editable     = $False
                hideControls = $True
                nav          = @(@{enable=$False
                                type = 'timepicker'})
                rows         = @(@{})
                style        = "dark"
                tags         = @()
                templating   = @{list = @()}
                time         = @{}
                timezone    = "browser"
                title        = "$DashboardTitle"
                version      = 5
                }
                expires = $Expires
                name = "$SnapshotName"
            
            } | ConvertTo-Json -Depth 4
            Method      = "POST"
            Uri         = "$($configuration.GrafanaUri)/snapshots"
            ContentType = "application/json"


        }

        Invoke-RestMethod @irmParams

    }
}
function New-GraphanaGraphPanel {

    [cmdletBinding()]
    Param(
        [Parameter(Mandatory,Position=0)]
        [String]
        $Title,

        [Parameter(Mandatory,Position=1)]
        [String]
        $Description,

        [Parameter(Mandatory,Position=2)]
        [String]
        $Datasource,

        [Parameter(Mandatory,Position=3)]
        [String]
        [ValidateSet('graph','singlestat','gauge','table','text','heatmap','alert list','dashboard list','plugin list')]
        $Type,
        
        [Parameter()]
        [Switch]
        $Transparent,

        [Parameter()]
        [Array]
        $valueMappings,

        [Parameter()]
        [Switch]
        $showThresholdLabels,

        [Parameter()]
        [Switch]
        $showThresholdMarkers,

        [Parameter()]
        [Int]
        $minValue,

        [Parameter()]
        [int]
        $thresholds_Index,

        [Parameter()]
        [string]
        $threshold_HexColor,

        [Parameter()]
        [int]
        $threshold_Value

        

    )

    begin {}

    process {
        $panelHash = @{
            
        }

    }

    end {}

}
function Remove-GrafanaApiKey {
    <#
    .SYNOPSIS
    Deletes an API key from your Grafana Instance
     
    .PARAMETER ApiId
    The ID of the API Key you wish to delete
     
    .EXAMPLE
    Remove-GrafanaApiKey -ApiId 6
 
    #>

    
    [cmdletBinding(SupportsShouldProcess=$true,ConfirmImpact="High",HelpUri="https://github.com/steviecoaster/PSGrafana/wiki/Remove-GrafanaApiKey")]
    Param(

    [Parameter(Mandatory,Position=0,ValueFromPipeline,ValueFromPipelineByPropertyName)]
    [Int]
    $ApiId

    )

    begin { $Null = Get-GrafanaConfig }

    process {

        If($PSCmdlet.ShouldProcess("ID: $ApiId","DELETE")){

            $header = @{ Authorization = "Bearer $($Configuration.apikey)"}
            
            $irmParams = @{

                Method = "DELETE"
                Uri = "$($Configuration.GrafanaUri)/auth/keys/$ApiId"
                Headers = $header
                ContentType = "application/json"
            }

            Invoke-RestMethod @irmParams

        }
    }
}
function Remove-GrafanaDashboard {
    <#
    .SYNOPSIS
    Remove a Grafana Dashboard via the API
     
    .DESCRIPTION
    This cmdlet exposes the API to delete a dashboard out of Grafana
     
    .PARAMETER Dashboard
    The friendly name of the Dashbaord to remove.
     
    .EXAMPLE
    Remove-GrafanaDashboard -Name FancyDash
 
    .EXAMPLE
    Get-GrafanaDashboard -Name FancyDash | Remove-GrafanaDashboard
 
    .EXAMPLE
    Remove-GrafanaDashbaord -Name WebFarmDev -Confirm:$false
     
    #>

    
    [cmdletBinding(SupportsShouldProcess,ConfirmImpact="High",DefaultParameterSetName="Default")]
    Param(
        [Parameter(Mandatory,Position=0,ParameterSetName="Default")]
        [Alias('Name')]
        [String]
        $Dashboard,

        [Parameter(Mandatory,ParameterSetName="Pipeline",ValueFromPipeline)]
        [PSObject]
        $InputObject


    )

    begin { $null = Get-GrafanaConfig }

    process { 

        Switch($PSCmdlet.ParameterSetName){

            'Default' {

                $Uid = Get-GrafanaDashboard -Name $Dashboard | Select-Object -ExpandProperty uid
                
            }

            'Pipeline' {

                $Uid = $($InputObject.uid)

            }

        }

        $irmParams = @{
            Method = "DELETE"
            Headers = @{ Authorization = "Bearer $($Configuration.apikey)"}
            ContentType = "application/json"
            Uri = "$($configuration.GrafanaUri)/dashboards/uid/$Uid"
        }

        If($PSCmdlet.ShouldProcess("Dashboard: $Dashboard", "DELETE")){
        $Result = Invoke-RestMethod @irmParams

        $Result

        }

    }

}
function Remove-GrafanaDatasource {
    <#
        .SYNOPSIS
        Removes the specified Grafana datasource
         
        .PARAMETER DatasourceId
        The ID of the datasource you wish to remove
         
        .PARAMETER DatasourceName
        The friendly name of the datasouce you wish to remove
         
        .EXAMPLE
        Remove-GrafanaDashboard -DatasourceId 3
         
        .EXAMPLE
        Remove-GrafanaDashboard -DatasourceName 'ElasticPuppies'
    #>

    [cmdletBinding(SupportsShouldProcess=$true,ConfirmImpact="High",HelpUri="https://github.com/steviecoaster/PSGrafana/wiki/Remove-GrafanaDatasource")]
    param(
        
        [Parameter()]
        [Int]
        $DatasourceId,

        [Parameter()]
        [String]
        $DatasourceName
    )

    begin { $null = Get-GrafanaConfig }

    process {

        $header = @{ Authorization = "Bearer $($Configuration.apikey)"}

        Switch($PSBoundParameters.Keys){
                
            'DatasourceId' {    
                
                    $irmParams = @{
                    
                    Method      = "DELETE"
                    Uri         = "$($configuration.GrafanaUri)/datasources/$DatasourceId" 
                    Headers     = $header
                    ContentType = "application/json"

                }

                If($PSCmdlet.ShouldProcess("DELETE","Datasource ID:$DatasourceId")){
                    
                    Invoke-RestMethod @irmParams
                
                }
            }

            'DatasourceName' {    
                
                $irmParams = @{
                    
                    Method      = "DELETE"
                    Uri         = "$($configuration.GrafanaUri)/datasources/name/$DatasourceName" 
                    Headers     = $header
                    ContentType = "application/json"

                }

                If($PSCmdlet.ShouldProcess("Datasource Name:$DatasourceName","DELETE")){
                    
                    Invoke-RestMethod @irmParams
                
                }

            }

        }

    }

}
function Remove-GrafanaFolder {
<#
.SYNOPSIS
Removes the specified folder from your Grafana instance
 
.DESCRIPTION
Removes the specified folder from your Grafana instance using the API. This is a highly destructive operation. Any Panels that are stored within the folder will be destroyed.
 
.PARAMETER Folder
The folder you wish to delete
 
.EXAMPLE
Remove-GrafanaFolder -Folder Duckies
 
#>


    [cmdletBinding(SupportsShouldProcess,ConfirmImpact="High")]
    Param(
        
        [Parameter(Mandatory,Position=0)]
        [String]
        $Folder
    )

    begin { $null = Get-GrafanaConfig }

    process {

        $Uid = Get-GrafanaFolder | Where-Object { $_.title -eq "$Folder" } | Select-Object -ExpandProperty uid

        $irmParams = @{
            
            Method      = "DELETE"
            Headers     = @{ Authorization = "Bearer $($Configuration.apikey)"}
            ContentType = "application/json"
            Uri         = "$($configuration.GrafanaUri)/folders/$Uid"

        }

        If($PSCmdlet.ShouldProcess("Folder: $Folder", "DELETE")){
        $return = Invoke-RestMethod @irmParams

        $return
        }
    }
}
function Remove-GrafanaSnapshot {
    <#
    .SYNOPSIS
    Remove a Grafana snapshot via the API
     
    .DESCRIPTION
    Grafana exposes an endpoint to delete snapshots. This cmdlet leverages that endpoint to let you remove them programmatically
     
    .PARAMETER SnapshotName
    The friendly name of the snapshot you wish to remove
     
    .EXAMPLE
    Remove-GrafanaSnapshot -SnapshotName SnappyMcSnapshoterson
     
    #>

    
    [cmdletBinding(SupportsShouldProcess,ConfirmImpact="High")]
    Param(
        
        [Parameter(Mandatory)]
        [String]
        $SnapshotName

    )

    begin { $null = Get-GrafanaConfig }

    process {

        $Key = Get-GrafanaSnapshot -SnapshotName $SnapshotName | Select-Object -ExpandProperty key

        $irmParams = @{
            
            Method = "DELETE"
            Headers     = @{ Authorization = "Bearer $($Configuration.apikey)"}
            ContentType = "application/json"
            Uri = "$($configuration.GrafanaUri)/snapshots/$key"

        }

        If($PSCmdlet.ShouldProcess("Snapshot: $SnapshotName", "DELETE")){
            
            Invoke-RestMethod @irmParams
        
        }

    }#process

}#function
function Set-GrafanaConfig {
    <#
        .SYNOPSIS
        Modifies the configuration file for the module
         
        .PARAMETER ConfigurationFile
        The path to the JSON configuration file. Defaults to Config\Grafana.json
         
        .PARAMETER APIKey
        Your new API Key
         
        .PARAMETER GrafanaUri
        The new Grafana uri
         
        .EXAMPLE
        Set-GrafanaConfig -APIKey '10395j23oi2r' -GrafanaUri 'https://test-grafana.mydomain.org'
 
    #>

    [cmdletBinding()]
    Param(
        [Parameter()]
        [String]
        $ConfigurationFile = "$PSScriptRoot\Config\Grafana.json",

        [Parameter()]
        [String]
        $APIKey,

        [Parameter()]
        [String]
        $GrafanaUri
    )


    begin { $config = Get-GrafanaConfig }

    process {

        Switch($PSBoundParameters.Keys){

            'APIKey' {
                $config.apikey = $APIKey
            }

            'GrafanaUri' { 
                $config.GrafanaUri = $GrafanaUri
            }
        }

        $config | ConvertTo-Json | Set-Content $ConfigurationFile
    }
}
function Set-GrafanaDashboard {
    <#
    .SYNOPSIS
    Update an existing Dashboard in Grafana
     
    .DESCRIPTION
    Change the title and tags of an existing Dashboard in Grafana
     
    .PARAMETER Title
    The title of the dashboard you wish to modify
     
    .PARAMETER NewTitle
    The new title of the Dashboard if you wish to change it
     
    .PARAMETER Tags
    The updated tags. This overwrites existing tags
     
    .PARAMETER DashboardId
    If you know the dashboard ID, you may enter it
     
    .PARAMETER DashboardUid
    If you know the dashboard Uid, you may enter it
     
    .EXAMPLE
    Set-GrafanaDashboard -Title "Boring Old Title" -NewTitle "Fancy New Title"
 
    .EXAMPLE
    Set-GrafanaDashboard -Title "Boring Old Title" -NewTitle "Fancy New Title" -Tags "prod","wizz_bang"
 
    .EXAMPLE
    Set-GrafanaDashboard -Title "Boring Old Title" -Tags "prod","apache" -DashboardId 35 -DashboardUid 5XWS256
     
    #>

    
    [cmdletBinding(DefaultParameterSetName="Update")]
    Param(
        [Parameter(Mandatory,Position=0,ParameterSetName="Update")]
        [String]
        $Title,

        [Parameter(Position=1,ParameterSetName="Update")]
        [String]
        $NewTitle,

        [Parameter(ParameterSetName="Update")]
        [String[]]
        $Tags,

        [Parameter(Mandatory,ParameterSetName="id")]
        [Int]
        $DashboardId,

        [Parameter(Mandatory,ParameterSetName="id")]
        [String]
        $DashboardUid
    )

    begin { $null = Get-GrafanaConfig }

    process {

        $irmParams = @{
            
            Headers = @{ Authorization = "Bearer $($Configuration.apikey)"}
            ContentType = "application/json"
            Method = "POST"
            Uri = "$($configuration.GrafanaUri)/dashboards/db"

        }

        $body = @{
            
            overwrite = $true

        }
        $dashboard = @{}

        if($NewTitle){
            
            $dashboard.Add("title",$NewTitle)

        }

        else{

            $dashboard.Add("title",$Title)

        }

       If($PSCmdlet.ParameterSetName -eq "id"){

        $dashboard.Add("id",$DashboardId)
        $dashboard.Add("uid",$DashboardUid)

       }

       else{

        $identifiers = Get-GrafanaDashboard -Name $Title | Select-Object id,uid,folderid

        $dashboard.Add("id",$identifiers.id)
        $dashboard.Add("uid",$identifiers.uid)

        $body.Add('folderId',$identifiers.folderid)

       }

       $body.Add("dashboard",$dashboard)

       $irmParams.Add("Body",($body | ConvertTo-Json))

       $return = Invoke-RestMethod @irmParams
       
       $return

    }
}
function Set-GrafanaFolder {
    <#
    .SYNOPSIS
    Update the Title of a Folder in Grafana
     
    .DESCRIPTION
    The API only allows updates to the Title of a folder in Grafana. This cmdlet accomplishes that task
     
    .PARAMETER OldTitle
    The current title of the Folder you wish to change
     
    .PARAMETER NewTitle
    The new title of the folder you wish to change
     
    .EXAMPLE
    Set-GrafanaFolder -OldTitle "FooBar" -NewTitle "FizzBuzz"
 
    Set the title of the folder FooBar to FizzBuzz
     
    .NOTES
     
    #>

    
    [cmdletBinding(HelpUri="https://github.com/steviecoaster/PSGrafana/wiki/Set-GrafanaFolder",SupportsShouldProcess=$true,ConfirmImpact="High")]
    Param(
        [Parameter(Mandatory,Position=0)]
        [String]
        $OldTitle,

        [Parameter(Mandatory,Position=1)]
        [String]
        $NewTitle
    )

    begin { $null = Get-GrafanaConfig }

    process {

        $Uid = Get-GrafanaFolder | Where-Object { $_.title -eq "$OldTitle" } | Select-Object -ExpandProperty uid
        $Version = Get-GrafanaFolder -Uid $uid | Select-Object -ExpandProperty version

        Write-Warning -Message "Modifying folder with Uid: $Uid and Version: $Version"

        $irmParams = @{
            
            Method      = "PUT"
            Headers     = @{ Authorization = "Bearer $($Configuration.apikey)"}
            ContentType = "application/json"
            Uri         = "$($configuration.GrafanaUri)/folders/$Uid?overwrite=true"
            Body        = (@{Title = $NewTitle}| ConvertTo-Json)

        }

        If($PSCmdlet.ShouldProcess("Folder: $OldTitle", "UPDATE")){
            
            Invoke-RestMethod @irmParams
        
        }

    }

}
function Set-GrafanaUser {
    [cmdletBinding()]
    Param(
        [Parameter(Mandatory,Position=0)]
        [String]
        $Username,

        [Parameter(Position=1)]
        [ValidateSet('default','light','dark')]
        [String]
        $Theme,

        [Parameter(Position=2)]
        [String]
        $FullName,

        [Parameter(Position=3)]
        [String]
        $EmailAddress,

        [Parameter(Position=4)]
        [String]
        $NewUsername,

        [Parameter(Mandatory,Position=5)]
        [PSCredential]
        $Credential

    )

    begin { $null = Get-GrafanaConfig }

    process {

        $User = Get-GrafanaUser -Username $Username -Credential $Credential

        $irmParams = @{
            
            Method = 'PUT'
            Authentication = "Basic"
            Credential = $Credential
            ContentType = "application/json"
            
        }

        If($($configuration.GrafanaUri) -match '^(http://)'){
                    
            $irmParams.Add('AllowUnencryptedAuthentication',$true)
        
        }

        $body = @{}

        Switch($PSBoundParameters.Keys){

            'Username' {

                $irmParams.Add('Uri',"$($configuration.GrafanaUri)/users/$($User.users.id)")
                $body.Add("login","$Username")

            }

            'Theme' {

                $body.Add('theme',"$Theme")
            }

            'FullName' {

                $body.Add("name","$FullName")

            }

            'EmailAddress' {

                $body.Add("email","$EmailAddress")

            }

            'NewUsername' {

                $body.Add("login","$NewUsername")

            }

        }#switch

        $body | ConvertTo-Json
        
        $irmParams.Add("body",($body | ConvertTo-Json))

        $result = Invoke-RestMethod @irmParams

        $result

    }#process

}#function
function Suspend-GrafanaAlert {
    <#
    .SYNOPSIS
    Pause a Grafana Alert by Name, ID, or pause ALL alerts in Grafana
     
    .DESCRIPTION
    This cmdlet provides a way to pause Grafana alerts via the API
     
    .PARAMETER AlertId
    The ID of the Grafana Alert you wish to pause
     
    .PARAMETER AlertName
    The Name of the Grafana Alert you wish to pause
     
    .PARAMETER All
    Pause all Grafana Alerts
     
    .PARAMETER Credential
    The credential to use to pause all Grafana alerts
     
    .EXAMPLE
    Suspend-GrafanaAlert -AlertId 12
 
    .EXAMPLE
    Suspend-GrafanaAlert -AlertName WebResponseTime
 
    .EXAMPLE
    Suspend-GrafanaAlert -All -Credential _username_
 
    .EXAMPLE
    Suspend-GrafanaAlert -All -Credential (Get-Credential)
     
    .NOTES
    The -Credential parameter is required when pausing all alerts. This is due to how the API handles the authentication header for that operation
 
    #>

     
    [cmdletBinding(SupportsShouldProcess,ConfirmImpact="High",DefaultParameterSetName="Name")]
    Param(
        [Parameter(ParameterSetName="Id")]
        [Int]
        $AlertId,

        [Parameter(ParameterSetName="Name")]
        [String]
        $AlertName,

        [Parameter(Mandatory,Position=0,ParameterSetName="All")]
        [Switch]
        $All,

        [Parameter(Mandatory,Position=1,ParameterSetName="All")]
        [System.Management.Automation.PSCredential]
        $Credential

    )

    begin { $null = Get-GrafanaConfig }

    process {

        function Test-Uri($uri) {

            $null = $uri -match '^((?<insecure>http://)|(?<secure>https://))'
    
        }

        Test-Uri -uri $configuration.GrafanaUri

        $irmParams = @{
            
            Method      = "POST"
            ContentType = "application/json"
            Body        = @{'paused' = $true} | ConvertTo-Json

        }

        Switch($PSCmdlet.ParameterSetName){

            'Id' {
                $irmParams.Add('Uri',"$($Configuration.GrafanaUri)/alerts/$AlertId/pause")
                $irmParams.Add("Headers",@{ Authorization = "Bearer $($Configuration.apikey)"})

                    If($PSCmdlet.ShouldProcess("Alert: $AlertId", "PAUSE")){

                        $result = Invoke-RestMethod @irmParams
                        $result
                    }
            }

            'Name' { 

                $Name = (Get-GrafanaAlert -AlertName $AlertName).id
                
                $irmParams.Add('Uri',"$($Configuration.GrafanaUri)/alerts/$Name/pause")
                $irmParams.Add("Headers",@{ Authorization = "Bearer $($Configuration.apikey)"})

                    If($PSCmdlet.ShouldProcess("Alert: $Alertname", "PAUSE")){

                        $result = Invoke-RestMethod @irmParams
                        $result
                    }

            }

            'All' {

                
                    $irmParams.Add("Uri","$($configuration.GrafanaUri)/admin/pause-all-alerts")
                    $irmParams.Add("Authentication","Basic")
                    $irmParams.Add("Credential",$Credential)

                    If($($configuration.GrafanaUri) -match '^(http://)'){
                    
                        $irmParams.Add('AllowUnencryptedAuthentication',$true)
                    
                    }

                    If($PSCmdlet.ShouldProcess("Alert: $Alertname", "PAUSE")){

                        $result = Invoke-RestMethod @irmParams
                        $result
                    }

                }            
            }

    }#process

}#function
$PublicFunctions = 'Get-GrafanaAlert', 'Get-GrafanaAnnotation', 'Get-GrafanaApiKey', 'Get-GrafanaConfig', 'Get-GrafanaDashboard', 'Get-GrafanaDatasource', 'Get-GrafanaFolder', 'Get-GrafanaOrg', 'Get-GrafanaOrgUser', 'Get-GrafanaServerHealth', 'Get-GrafanaServerSettings', 'Get-GrafanaSnapshot', 'Get-GrafanaUser', 'New-GrafanaAPIKey', 'New-GrafanaDashboard', 'New-GrafanaFolder', 'New-GrafanaSnapshot', 'New-GraphanaPanel', 'Remove-GrafanaApiKey', 'Remove-GrafanaDashboard', 'Remove-GrafanaDatasource', 'Remove-GrafanaFolder', 'Remove-GrafanaSnapshot', 'Set-GrafanaConfig', 'Set-GrafanaDashboard', 'Set-GrafanaFolder', 'Set-GrafanaUser', 'Suspend-GrafanaAlert'
If(!(Test-Path $PSScriptRoot\Config\Grafana.json)){
    $grafanaConfig = @{
        
    }
    Write-Host "No config file found in Config folder. Assuming first run..." -ForegroundColor yellow
    Write-Host "We will now ask some questions to get things setup" -ForegroundColor yellow
    $GrafanaUri = Read-Host -Prompt "What is your base Grafana uri?"

    Write-Host "Adding URI and appending /api to config file..." -ForegroundColor yellow
    $grafanaConfig.Add('GrafanaUri',"$GrafanaUri/api")

    $ApiKey = Read-Host -Prompt "What is your API Key? Found at https://$GrafanaUri/org/apikeys"

    Write-Host "Adding API Key to config file..." -ForegroundColor yellow
    $grafanaConfig.Add('apikey',$ApiKey)

    $grafanaConfig | ConvertTo-Json | Out-File $PSScriptRoot\Config\Grafana.json

    Write-Host "Config file has been generated successfully. Run 'Get-GrafanaConfig' to verify" -ForegroundColor yellow
    
}