Disconnected Devices Cleanup Using the Console or PowerShell

Follow these best practices to clean up disconnected devices.

Disconnected Devices Cleanup Using the Automox Console

Follow these steps to clean up disconnected devices using the console.

  1. Go to Devices in the console.
  2. Select Columns on the right-hand side of the window.
  3. Next, select the Disconnected For option in the Columns drop-down menu.
  4. Sort by “Disconnected For” to get a list of devices based on how many days they have been disconnected.
  5. Select all the devices greater than X amount of days.
           a. In this example, we are selecting anything older than 45 days.
  6. Finally, click the Actions drop-down menu and select Remove.
  7. All devices disconnected for more than X days are immediately removed from the console with this action.

Disconnected Devices Cleanup Using PowerShell

Follow these best practices to clean up disconnected devices using a PowerShell script.

You can use a PowerShell script to remove devices that have been disconnected longer than X days.

This script automates the removal using an API call to check the last disconnected date and remove any devices older than the number of days you specify in the code.

There are four areas in the code that you’ll need to update to get the script to function:

  1. $orgID = 'YOUR_ORG_ID'
    You will need your Org ID, which can be found by looking at the URL. Select the value after the "?o="

    Note: The user must be a Global or Zone administrator to manage API keys for a zone. See Managing Keys for more information.

  2. $apiKey = 'YOUR_API_KEY'
    In your console, go to Settings > Keys and select the API key. Note that the API key is per user, so that another user will have different API keys.
  3. $maxDays = 120  
    Any device that has been disconnected for more than 120 days is deleted from the console. You can adjust this to the number of days you prefer.
  4. $logPath = 'C:\temp\'
    Set this variable to the folder of your choosing.

After you make these four changes, you can run the script on any Windows devices using PowerShell.

Running the Script in Test Mode

To run the disconnected devices script in a TEST mode to see what will be deleted, update these lines as follows:

1. Uncomment this line:

#echo "device: $serverName `t last disconnected date: $lastCheckin `t days disconnected: $span.Days"

2. Comment out this line:

$delResponse = Invoke-WebRequest -UseBasicParsing -Method Delete -Uri $delURI

Remove Old Disconnected Devices Script

Note: This script automatically removes devices from your console and this is not a reversible operation. If you unintentionally remove a device using this script, you must reinstall the agent to return the device to the console.

#    [-------------------------------------DISCLAIMER-------------------------------------]
#    This script is provided as-is with no implicit
#     warranty or support. It's always considered a best practice
#     to test scripts in a DEV/TEST environment, before running them
#     in production.
#     Please proceed with caution.
#     Do not distribute your API Key to any untrusted 3rd party.
#    [-------------------------------------DISCLAIMER-------------------------------------]

#     The SETUP section gets your API return and is not specific to any particular use-case.
#     The OPERATIONAL section is specific to one scenario and can be overhauled for your specific uses.

############################# SETUP Section #############################

#modify log path as desired
$logPath = 'C:\temp\'

#Easier to maintain, especially if multiple organizations, or for repurposing for different API Tables
$apiInstance = 'https://console.automox.com/api/'
$apiTable = 'servers'

#replace the two variables below with your Org ID and your API key
$orgID = 'YOUR_ORG_ID'
$apiKey = 'YOUR_API_KEY'
$orgAndKey = "?o=$orgID&api_key=$apiKey"

#Number of days disconnected before deleting - adjust to your desired range
$maxDays = 120
#optional query to filter, if the whole server list is too long, you could add the date filter here
$query = ''

#initialize empty arrays to store server IDs to be deleted
$toDelete = @()
$failDelete = @()
$successDelete = @()

#put components together
$getURI = $apiInstance + $apiTable + $orgAndKey + $query

#Get the json body of the Web Request
$jsonReturn = (Invoke-WebRequest -UseBasicParsing -Method Get -Uri $getURI).Content

#Convert to object with manipulatable properties/values
$servers = $jsonReturn | ConvertFrom-Json

#Export to C

############################# END Setup Section #############################


############################# OPERATIONAL Section #############################

#Check each server for checkin time, conditionally take action
foreach ($server in $servers) {
    #pull out wanted details
    $serverID = $server.id
    $serverName = $server.name

    #check to make sure last_disconnect_time isn't null, which it will be for currently connected devices, in which case the lastcheckin variable will be set to today's date
    $lastCheckin = Get-Date
    if ($server.last_disconnect_time) {
        $lastCheckin = [datetime]$server.last_disconnect_time
        }

    #Calculate time since last checking to now
    $span = New-TimeSpan -Start $lastCheckin

    #uncomment line below if you want to see all the servers with their last disconnect time and number of days disconnected for troubleshooting
    #echo "device: $serverName `t last disconnected date: $lastCheckin `t days disconnected: $span.Days"

    if ($span.Days -ge $maxDays) {
        #Delete or data collection code here

        #Delete method takes serverID only

        #Hardcoded would look like this $delURI = https://console.automox.com/api/servers/$serverID?o=YOUR_ORG_ID&api_key=YOUR_API_KEY

        $toDelete += @{"ServerName"=$serverName;"ServerID"=$serverID;"last_disconnect_time"=$lastCheckin}
        $delURI = $apiInstance + $apiTable + '/' + $serverID + $orgAndKey

        #Attempt to delete and track failures
        try {
            $delResponse = Invoke-WebRequest -UseBasicParsing -Method Delete -Uri $delURI
            Write-Output "Successfully Deleted Server: $serverName"
            $successDelete += @{"ServerName"=$serverName;"ServerID"=$serverID;"last_disconnectn_time"=$lastCheckin}
        }
        catch {
            $failDelete += @{"ServerName"=$serverName;"ServerID"=$serverID;"last_disconnect_time"=$lastCheckin}
            Write-Output "Failed to Delete Server: $serverName"
        }
    }
    #Output logging into json files for later review/manipulation
    $toDelete | ConvertTo-Json | Out-File $logPath\ToBeDeleted.json
    $successDelete | ConvertTo-Json | Out-File $logPath\Delete_Success.json
    $failDelete | ConvertTo-Json | Out-File $logPath\Delete_Failed.json}
}

Related Topics: