API query in PowerShell

Use of the API, regardless of the queried route, requires authentication by following this process.

In the code below, the “username” and “password” keywords must respectively be replaced by the values “API access key ID” and “API secret access key” of the credentials previously generated. The same applies to the “url” value, which should be replace by your Cyberwatch instance IP address.

In general, you just need to modify the queried URL, used method and body content of the following snippets in order to make a specific API request using this cmdlet.

In case the TLS certificate of the Cyberwatch server cannot be recognized by the machine running this script, it is necessary to execute the following code snippet before those snippets:

add-type @"
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    public class TrustAllCertsPolicy : ICertificatePolicy {
        public bool CheckValidationResult(
            ServicePoint srvPoint, X509Certificate certificate,
            WebRequest request, int certificateProblem) {
            return true;
        }
    }
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy

Basic authentication snippet in PowerShell

This code allows you to run an API connection test on your Cyberwatch instance:

$api_url = "https://localhost"
$credentials = "access_key:secret_key"
$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($credentials))

$response = Invoke-WebRequest -URI $api_url/api/v3/ping -Method Get -Headers @{
    "Accept" = "application/json; charset=utf-8"
    Authorization = "Basic $encodedCreds"}

$response.Content

Group creation using Post request snippet in PowerShell

This code allows you to create a new group on your Cyberwatch instance:

$api_url = "https://localhost"
$credentials = "access_key:secret_key"
$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($credentials))

$body = @{
    "name" = "nom_du_groupe"
    "description" = "description_du_groupe"
    "color" = "#da13b4"
} | ConvertTo-Json

$response = Invoke-WebRequest -URI $api_url/api/v3/groups -Method POST -Body $body -Headers @{
    "Accept"      = "application/json; charset=utf-8"
    "Content-Type" = "application/json"
    Authorization = "Basic $encodedCreds"
}

$response.Content

Back to top