#Input Prompts (if required, otherwise comment out and enable the user/pass lines below and hard-code) $user = Read-Host 'Enter API Username' $pass = Read-Host 'Enter API Password' $host_name = Read-Host 'Application Server IP' $pair = "${user}:${pass}" $contentType = "application/json" #Encode the string to the RFC2045-MIME variant of Base64, except not limited to 76 char/line. $bytes = [System.Text.Encoding]::ASCII.GetBytes($pair) $base64 = [System.Convert]::ToBase64String($bytes) #Create the Auth value as the method, a space, and then the encoded pair Method Base64String $basicAuthValue = "Basic $base64" #Create the header Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== $headers = @{ Authorization = "$basicAuthValue" } #reset counters #$clusters = $null #$total_clusters = $null #$pages = $null #ensure all certs are accepted 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 #Invoke the web-request to to collect a list of clusters and loop through each page. Cluster API allows only 100 results max, so will need to adjust paging $pages = [math]::Round((Invoke-RestMethod "https://$host_name/securitymanager/api/domain/1/cluster" -Headers $headers).total/100) foreach ($pagenum in 0..$pages) { $clusters = (Invoke-RestMethod "https://$host_name/securitymanager/api/domain/1/cluster?page=$pagenum&pageSize=100" -Headers $headers).results | select -ExpandProperty id $total_clusters = $total_clusters + @($clusters) } foreach ($cluster in $total_clusters) { $cluster_properties = Invoke-RestMethod https://$host_name/securitymanager/api/domain/1/cluster/$cluster -ContentType $contentType -Headers $headers # If the deviceIds field is blank for a cluster object, it has no members so can be deleted. if ([string]::IsNullOrEmpty($cluster_properties.deviceIds)) { write-host "deleting cluster id $cluster as it is empty" Invoke-RestMethod -Method DELETE https://$host_name/securitymanager/api/domain/1/cluster/$cluster -ContentType $contentType -Headers $headers} else # Do not delete the cluster if it contains a deviceId value {write-host "cluster id $cluster has deviceIds skipping"} }