Functions/Remove-DatabricksClustersFromWorkspace.ps1

<#
.SYNOPSIS
Removes DataBricks Clusters from a workspace.
 
.DESCRIPTION
Removes DataBricks Clusters from a workspace.
 
.PARAMETER config
Configuration json file from the environment to use for possible clusters to remove.
 
.PARAMETER bearerToken
Your Databricks Bearer token to authenticate to your workspace (see User Settings in Datatbricks WebUI)
 
.EXAMPLE
Remove-DatabricksClustersFromWorkspace -config $config -bearerToken 'dapi1234567890'
 
.NOTES
Author: Sabin IO
 
#>
 
Function Remove-DatabricksClustersFromWorkspace {
    [cmdletbinding()]
    Param(
        [parameter(Mandatory = $true)]$config,
        [parameter(Mandatory = $true)][string]$bearerToken 
    )
    
    try {
        $clusters = Get-DatabricksClusters -BearerToken $bearerToken -Region $config.Region 
        $noneExistantClusters = @()
        $existentClusters = @()
    
        if ($config.removeClustersByName) {
            Write-Output "removeClustersByName config key supplied"
            if ($config.removeClustersByName.Length -ge 1) {
                if ($config.removeClustersByName[0].ToString().ToUpper() -eq "ALL") {
                    Write-Error "Removing all clusters is not recommended. "
                }
                else {
                    # Check if clusters exist in the first place
                    foreach ($cluster in $config.removeClustersByName) {
                        if ($cluster -notin $clusters.cluster_name) {
                            $noneExistantClusters += $cluster
                        }      
                        else {
                            $existentClusters += $cluster
                        }          
                    }
                    if ($noneExistantClusters) {
                        Write-Warning "There are clusters that do not exist to remove, These will be skipped. `n`n $($noneExistantClusters)"

                    }
                    # If we've got this far, it should mean we are good to remove all the known clusters by name
                    foreach ($cluster in $existentClusters) {
                        Remove-DatabricksCluster -BearerToken $bearerToken -Region $config.Region -ClusterName $cluster -Verbose           
                    }
                }           
            } 
        }     
        else {
            Write-Output "removeClustersByName config key not supplied"
        }
    }    
    catch {
        #uh oh
        throw $_.Exception
    }
}