Powershell example script using REST webservices DELETE node

iKnow-IT banner

Below you can find a powershell script to DELETE a node on a REST web services server.

$NodeToDelete = "$Node"
$BaseUrl = "< baseurl >"
$nodesURL = "/services/rest/cis/v1/nodes"
$RequestTimeout = 100000 # webrequest timeout in milliseonds
$UserName = "< user >"
$Password = "< passwd >"
$password_base64 = ConvertTo-SecureString $Password -AsPlainText -Force
$creds = New-Object System.Management.Automation.PSCredential ($UserName, $password_base64)
$Logfile = "$($Env:LogFiles)\DeleteNode.log"
# Functions
Function LogFile ($Type,$Message) {
$Date = get-date -format "yyyy-MM-dd HH:mm:ss"
Out-File -filepath $Logfile -inputobject "$($Date) [$($Type)] $($Message)" -append
Write-Host "$($Date) [$($Type)] $($Message)"
}

# Trust all certificates to avoid certiticate issues with HTTPS
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;
}
}
"@ # Do not add a TAB at this line or the script will fail

[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy

Logfile "INFO" "-------------------------- Start --------------------------"

# Create a request
Logfile "INFO" "Start request to get list of nodes: $($BaseUrl)$($nodesURL)"
Logfile "INFO" "Searching for name $($NodeToDelete)"

Try {
$response = Invoke-RestMethod "$($BaseUrl)$($nodesURL)" -Method Get -Credential $creds
}
Catch {
$res = $_.Exception.Response

Logfile "ERROR" "Error message: $([int]$res.StatusCode) $($res.StatusCode)"
LogFile "ERROR" "Exit script"
Logfile "INFO" "-------------------------- End --------------------------"
Exit 10
}

foreach ($rsp in $response) {
if ($rsp.name.ToLower().Contains($NodeToDelete.ToLower())) {
Logfile "INFO" "Name found: $($rsp.name)"
Try {
$deletersp = Invoke-RestMethod "$($BaseUrl)$($nodesURL)/$($rsp.name)" -Method Delete -Credential $creds
}
Catch {
$res = $_.Exception.Response

if ([int]$res.StatusCode -eq 404)
{
Logfile "INFO" "Response: $([int]$res.StatusCode) $($res.StatusCode)"
Logfile "INFO" "-------------------------- End --------------------------"
Exit
}
else
{
Logfile "ERROR" "Error message: $([int]$res.StatusCode) $($res.StatusCode)"
LogFile "ERROR" "Exit script"
Logfile "INFO" "-------------------------- End --------------------------"
Exit 10
}

}

break
}
}

Logfile "INFO" "-------------------------- End --------------------------"