Powershell script to move devices that have been disconnected longer than X days to a group

So you want to audit your devices that haven’t been connected for a long time, but you’re not prepared to delete them yet and just want to move them to their own group? Currently you can do this on the devices page by sorting by Last Disconnected Date and selecting devices to Assign to Group. However, this can become unwieldy if you have pages and pages of devices to move.

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

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

  1. $orgID = 'YOUR_ORG_ID' - put your Org ID, which can be found by looking at the URL of your console and selecting the value after the “?o=”: https://console.automox.com/dashboard?o=999999 . In this example URL the Org ID is the 999999 portion.

  2. $apiKey = 'YOUR_API_KEY' - in your console, go to Settings->API and select the API key. Note that the API key is per admin user, so you and another admin in your console will have different API keys.

  3. $srvGroup = 'GROUP_ID#_TO_MOVE_TO' - put your Group ID you want the devices moved to, which can be found by viewing the group page that lists devices in that particular group and grabbing the value after “groupId=” in the URL. One way to get to that page is to go to the System Mgmt page then find the group you want to move them to and click the little computer icon with a number under it.

  4. $maxDays = 120 - any device that has been disconnected for more than 120 days will be moved to the group you specify. You can adjust this to the number of days you prefer.

  5. $logPath = 'C:\temp\' - set this to the folder of your choosing

By default, the script will move all devices older than $maxDays, but if you prefer to only move Windows 7/8/10 workstations, there’s a alternate IF statement you can use on line 61.

Once you’ve made those changes, you can run the script below on any Windows device using Powershell.

Move Old Disconnected Devices Script:

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

#replace the variables below with your Org ID, API key, server group to move to, & number of days disconnected before moving
$orgID = 'YOUR_ORG_ID'
$apiKey = 'YOUR_API_KEY'
$srvGroup = 'GROUP_ID#_TO_MOVE_TO'
$maxDays = 120

#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'
$orgAndKey = "?o=$orgID&api_key=$apiKey"

#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 moved
$toMove = @()
$failMove = @()
$successMove = @()

#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

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

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

#Check each server and conditionally take action
foreach ($server in $servers) {
    #pull out wanted details
    $serverID = $server.id
    $serverName = $server.name
    $serverOS = $server.os_name
    $serverVer = $serverOS.Substring(0,1)
    
    #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"
    
    ###########################
    # Checking for all Systems.  If you want to include only Win 7/8/10 systems (no servers), use this IF statement instead and remark out the other if statement:
    ###########################
    # if ($span.Days -ge $maxDays -and ($serverVer -eq '1' -or $serverVer -eq '8' -or $serverVer -eq '7')) {
        
        if ($span.Days -ge $maxDays) {

        #Move method takes serverID only
        #Hardcoded would look like this $moveURI = https://console.automox.com/api/servers/$serverID?o=YOUR_ORG_ID&api_key=YOUR_API_KEY
                
        $toMove += @{"ServerName"=$serverName;"ServerID"=$serverID;"last_disconnect_time"=$lastCheckin}
        $moveURI = $apiInstance + $apiTable + '/' + $serverID + $orgAndKey
        
        #Attempt to move and track failures
        try { 
            $headers = @{
                "Authorization" = "Bearer $apiKey"
                "Content-Type" = "application/json"
            }
            $body = @"
            {
                "server_group_id": $srvGroup
            }
"@

            $moveResponse = Invoke-WebRequest -Method Put -Uri $moveURI -Headers $headers -Body $body
            Write-Output "Successfully Moved Server: $serverName"
            $successMove += @{"ServerName"=$serverName;"ServerID"=$serverID;"last_disconnect_time"=$lastCheckin}
        }
        catch { 
            $failMove += @{"ServerName"=$serverName;"ServerID"=$serverID;"last_disconnect_time"=$lastCheckin}
            Write-Output "Failed to Move Server: $serverName" 
        }
    }

    #Output logging into json files for later review/manipulation
    $toMove | ConvertTo-Json | Out-File $logPath\ToBeMoved.json
    $successMove | ConvertTo-Json | Out-File $logPath\Move_Success.json
    $failMove | ConvertTo-Json | Out-File $logPath\Move_Failed.json
}    

If you have any questions or problems getting this to function correctly please let us know!

4 Likes