Pete Hinchley: Remove a User's Account from Cisco Unity via the HTTP REST API using PowerShell

Here is some code I wrote this week to remove a user's account from Cisco Unity via the REST API using PowerShell. There are a few parts to the solution:

  1. A query is initiated to retrieve the user's account.
  2. The script aborts if a single record is not returned.
  3. The unique object id of the retrieved user account is obtained.
  4. A request to delete the matched user is submitted using the object id of the account.

To use the code, set the login variable to the login id of the user to be deleted, the username and password variables to those of an account with administrator privileges within Cisco Unity, and the api variable to the user REST API endpoint relevant to your environment.

I am sure this is a fairly niche task, but I hope someone may find the code useful.

# the login id of the user to delete.
$login = 'jbloggs'

# creds for connecting to the api.
$username = 'admin'
$password = 'password'

# api endpoint.
$api = 'https://10.1.1.1/vmrest/users'

# build authorization header.
$cred = [system.text.utf8encoding]::utf8.getbytes($username + ':' + $password)
$auth = 'BASIC ' + [system.convert]::tobase64string($cred)

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; }
  }
"@

# used to bypass certificate validity check.
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy

# build the request uri for retrieving the user by login id.
$query = '?query=(alias is {0})' -f $user
$request = $api, $query -join '/'

try {
  $result = invoke-restmethod $request -method GET -headers @{Authorization = $auth}
} catch { write-warning 'Error retrieving the account in Cisco Unity.'; exit }

if ($result.users.total -eq 0) { write-host 'User does not have an account in Cisco Unity.'; exit }
if ($result.users.total -gt 1) { write-host 'Unable to disambiguate the user account in Cisco Unity.'; exit }

# build a request for deleting the user based on the unique object id of the account.
$request = $api, $result.Users.FirstChild.ObjectId -join '/'

try {
  $result = invoke-restmethod $request -method DELETE -headers @{Authorization = $auth}
} catch { write-warning "Error deleting the user's account in Cisco Unity."; exit }