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

  • 24 September 2020
  • 1 reply
  • 407 views

Userlevel 5

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 “gid=” in the URL.




  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. You can also customize further by choosing specific OSs for the systems you want moved. Here are the values for $serverVer you can set in the IF statement:

1 = Windows 10

8 = Windows 8

7 = Windows 7

O = OSX

S = Server 20XX (Windows)

U = Ubuntu

C = CentOS

D = Debian


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


Move Old Disconnected Devices Script:


<#

.NOTES
Version 2.0
Updated to include pagination
Date: April 26, 2021

#>

############################# 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\'

$page = 0
$limit = 500
$servers = @()

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

#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 = @()

while($true) {

$orgAndKey = "?o=$orgID&api_key=$apiKey&l=$limit&p=$page"

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

#Get the json body of the Web Request
$resp = (Invoke-WebRequest -Method GET -Uri $uri -UseBasicParsing).Content | ConvertFrom-Json | Select-Object results

$servers += $resp.results
$page += 1

if($resp.results.count -lt $limit) {
break
}
}

############################# 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 ($server.server_group_id -ne $srvGroup) `
# -and ($serverVer -eq '1' -or $serverVer -eq '8' -or $serverVer -eq '7' -or $serverVer -eq 'O')) {

if (($span.Days -ge $maxDays) -and ($server.server_group_id -ne $srvGroup)) {

#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!


1 reply

Userlevel 3

Hi Tony, this only half works for me.


It does move devices older than X days, however not all of them.

Have a fair few disconnected devices that are missed.


Does anything need to be updated in this script now that the API has changed?


Also, what amendments would you need to make to return the devices that start ‘connecting’?

I.e. move devices that havent reported in 30 days to ‘OLD’ group, but then if they’ve connected again they get moved back to ‘ALIVE’ group?

Reply