teamviewer.com link icon
or
Ask The Community

Script for deleting obsolete computer account and revoke disabled/inexistant user account in AD

The following script performs below actions:

- Delete any TV computer that does not exist in company Active Directory or didn't report to TV Console for specified consecutive days.

- Revoke user access if the user account does not either exist or disabled.

Here is a script that I wrote to achieve the above requirements:

<#
.SYNOPSIS
This script manages TeamViewer Online Accounts.

.DESCRIPTION
This script helps removing any inactive device which was not connected to specified number of consecutive days using parameter $DevInactiveDays
and revokes the user access if the user account is either disabled or not exists in company AD.

.PARAMETER DevInactiveDays
Number of consecutive days that a device is not connected to TV Console

.PARAMETER TVAPIKey
TeamViewer API Key used to connect to TV Management Console

.PARAMETER activateLog
Enable log

.PARAMETER logFile
Specify the log file path and name. To be used with -activeLog $True

.PARAMETER Test
Simulate without performing any change.

.PARAMETER ListOnly
List only computers and users account.

.NOTES
Author : Sutha.S
Version : 1.0
Creation Date: 22-May-2019
#>

Param (
[Parameter(Mandatory=$true)]
[string] $TVAPIKey,
[Parameter(Mandatory=$true)][int] $DevInactiveDays,
[bool] $activateLog,
[string] $logFile,
[bool] $Test,
[Switch] $ListOnly
)

if ($activateLog -and $logFile) {Start-Transcript -Path $logFile -Force -Append}

$bearer = "Bearer",$TVAPIKey
$header = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$header.Add("authorization", $bearer)
$header.Add("Content-Type","application/json")
$DelComp = $False
$RvkUsr = $False

Write-Host "User Supplied parameters"
Write-Host " Device Inactive Days: " $DevInactiveDays
Write-Host " Activate Log: " $activateLog
Write-Host " Test mode: " $Test
Write-Host " Log file name: " $logFile
Write-Host

# Collecting computers from TV Mgmt Console
try {
Write-Host "Please standby while enumering all registered TV machines..."
$machines = Invoke-RestMethod -Uri "https://webapi.teamviewer.com/api/v1/devices" -Method Get -Headers $header -ErrorAction SilentlyContinue -ErrorVariable oErr
}
catch {
Write-Host "Error encountered while enumering devices: "
$_.Exception
}

if (!$oErr) {
$devArr = @()

ForEach($dev in $machines.devices)
{
try {
$devADAcc = Get-ADComputer -Filter ('Name -eq "{0}"' -f $dev.alias) -Properties Enabled | Select-Object Enabled

if (!$devADAcc) {$devADAcc = New-Object PSObject -Property @{'Enabled' = "NA"}}
}

catch {
$_.Exception
if ($activateLog -and $logFile) {Stop-Transcript}
Exit 1
}

$devArr += New-Object PSObject -Property @{
'Computer Name' = $dev.alias
'Device ID' = $dev.device_id
'AD Account Status' = $devADAcc.Enabled
'Last Seen' = $dev.last_seen
'Online State' = $dev.online_state -Join ", "
}

if ($dev.last_seen) {
$datediff = (NEW-TIMESPAN -Start $dev.last_seen -End (get-date -format yyyy-MM-ddTHH:mm:ssZ)).days
} Else {
$datediff = 0
}

if ($devADAcc.enabled -like "NA" -and $datediff -gt $DevInactiveDays -and $dev.online_state -ceq "Offline") {
$dt = Get-Date
$DelComp = $True

if (!$ListOnly) {
if ($Test) {
Write-Host "[" $dt "] Device" $dev.alias "didn't report for last" $datediff "consecutive days and could be deleted."
} else {
Write-Host "[" $dt "] Device" $dev.alias "didn't report for last" $datediff "consecutive days. So deleting it..."

# Deleting a device which is not found in AD and didn't report more than specified consecutive days.
$uri = "https://webapi.teamviewer.com/api/v1/devices/"+$dev.device_id
$retResult = Invoke-RestMethod -Uri $uri -Method Delete -Headers $header -ErrorAction Continue -ErrorVariable oErr

if ($oErr) {Write-Host " Failed to delete due " $oErr} else {Write-Host " Successfully deleted."}
}
}
}
}

if (!$DelComp -and !$ListOnly) {Write-Host " No computer account found with specified criteria to be deleted!"}

if ($ListOnly) {$devArr|FT -Property "Computer Name", "Online State", "Device ID", "AD Account Status", "Last Seen" -AutoSize}
}

# Collecting users from TV Mgmt Console
try {
Write-Host "Please standby while enumering all users account..."
$users = Invoke-RestMethod -Uri "https://webapi.teamviewer.com/api/v1/users?full_list=true" -Method Get -Headers $header -ErrorAction SilentlyContinue -ErrorVariable oErr
}
catch {
Write-Host "Error encountered while enumering users: "
$_.Exception
}

if (!$oErr) {


$usrArr = @()

ForEach($usr in $users.users)
{
try {
$usrADAcc = Get-ADUser -Filter ('EmailAddress -eq "{0}"' -f $usr.email) -Properties Enabled | Select-Object Enabled

if (!$usrADAcc) {$usrADAcc = New-Object PSObject -Property @{'Enabled' = $False}}
}

catch {
$_.Exception
if ($activateLog -and $logFile) {Stop-Transcript}
Exit 1
}

$usrArr += New-Object PSObject -Property @{
'User ID' = $usr.id
'Name' = $usr.name
'Email' = $usr.email
'Permissions' = $usr.permissions
'AD Account Status' = $usrADAcc.Enabled
'active' = $usr.active -Join ", "
}

if ($usrADAcc.Enabled -eq $False) {
$dt = Get-Date
$RvkUsr = $True

if (!$ListOnly) {
if ($Test) {
Write-Host "[" $dt "] User" $usr.name "active directory account is disabled and can be revoked."
} else {
$body = @{
active = $false;
}|ConvertTo-Json

Write-Host "[" $dt "] User" $usr.name "active directory account is disabled. So revoking this user access..."

# Revoke a user account if the user AD account is disabled
$uri = "https://webapi.teamviewer.com/api/v1/users/"+$usr.id
$retResult = Invoke-RestMethod -Uri $uri -Method Put -Headers $header -Body $body -ErrorAction Continue -ErrorVariable oErr

if ($oErr) {Write-Host " Failed to revoke the account due error" $oErr} else {Write-Host " Successfully revoked."}
}
}
}
}

if (!$RvkUsr -and !$ListOnly) {Write-Host " No user account found with specified criteria to be revoked!"}
if ($ListOnly) {$usrArr|FT -Property "Name", "Email", "User ID", "Active", "AD Account Status", "Permissions" -AutoSize}
}

if ($activateLog -and $logFile) {Stop-Transcript}

The parameters TVAPIKEY and DevInactiveDays are mandatory.

You need to create an API token which should have following access:

     Access Level = User
    User management = Create users, view users, edit users
    Group management = Read groups
   Computers & Contacts = View entries, add entries, edit entries, remove entries

To list users and computers, invoke the following command:

.\PScript.ps1 -TVAPIKey your_api_key -DevInactiveDays whatever_the_number -ListOnly

To delete any computers which didn't report for the past 30 days:

.\PScript.ps1 -TVAPIKey your_api_key -DevInactiveDays 30

To evaluate without applying the change:

.\PScript.ps1 -TVAPIKey your_api_key -DevInactiveDays whatever_the_number -Test

Enable logging by by activating switches:

-activateLog $True -logFile "file_path_name"

Hope this post is helpful!

Comments

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!