PrivateFunctions/Upload-ChecksToApi.ps1

Function Upload-ChecksToApi
{
  [CmdletBinding()]
  Param(
    [Parameter(Mandatory=$True)]
    [ValidateNotNull()]
    [Object[]] $ChecksToUpload,

    [Parameter(Mandatory=$True)]
    [ValidateNotNullOrEmpty()]
    [String] $CheckStatementRootPath
  )

  Validate-Context

  [Array]$ExistingCustomChecks = Get-DqChecks -CustomOnly

  $Imported = 0;
  Write-Verbose "Uploaden van controles naar DQ Monitor API..."

  ForEach($Check in $ChecksToUpload)
  {
    $ExistingCheck = $ExistingCustomChecks | Where-Object { $_.Name -eq $Check.check.name }
    $CheckData = [System.Text.Encoding]::UTF8.GetBytes(($Check | ConvertTo-Json))

    Try
    {
      Write-Verbose "Controle '$($Check.check.name)' uploaden..."      
      If ($ExistingCheck)
      {
        $Url = "$($DqContext.GetCheckControllerUrl())/$($ExistingCheck.id)"
        $Response = Invoke-WebRequest -UseBasicParsing -Uri $Url -Method Put -Header $DqContext.Headers -Body $CheckData
      }
      Else
      {
        $Response = Invoke-WebRequest -UseBasicParsing -Uri $DqContext.GetCheckControllerUrl() -Method Post -Header $DqContext.Headers -Body $CheckData
      }
      
      If ($ExistingCheck)
      {
        Write-Host "Controle '$($Check.Check.Name)' is geüpdatet."
      }
      Else 
      {
        Write-Host "Controle '$($Check.Check.Name)' is opgevoerd."
      }

      $Imported += 1;
    }
    Catch [System.Net.WebException]
    {
      $Stream = $_.Exception.Response.GetResponseStream()
      $StreamReader = New-Object System.IO.StreamReader($Stream)
      $StreamReader.BaseStream.Position = 0
      $ResponseBody = $StreamReader.ReadToEnd() | ConvertFrom-Json -ErrorAction SilentlyContinue
      $StreamReader.Close()
   
      $ErrorMessage = "Fout bij opvoeren/uploaden controle '$($Check.check.name)': '$($_.Exception.Message)'."
      If ($ResponseBody -and $ResponseBody.Message)
      {
        $ErrorMessage = $ErrorMessage + [char]10 + [char]13 + " + DetailedMessage: $($ResponseBody.Message)"
      }
            
      Write-Warning $ErrorMessage
    }
  }

  Write-Host "$($Imported) controle(s) opgevoerd."
}