Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Removes Agent records from your Inventory Server's database.
# Written by Colby Bouma
# This script removes all Agent records associated with the computer name you specify
#
# v 011
[CmdletBinding()]
param (
[string]$Name,
[string]$InventoryDBFile = "$env:SYSTEMDRIVE\ProgramData\Admin Arsenal\PDQ Inventory\Database.db"
)
if ( -not ( Test-Path "$InventoryDBFile" ) ) {
Write-Error "Unable to find database $InventoryDBFile"
Exit 10
}
function Send-Query ([string]$Query) {
$QueryOutput = sqlite3.exe "$InventoryDBFile" "$Query" 2>&1
# I borrowed the error handling from this, but kind of went my own way with it
# http://serverfault.com/questions/340711/redirect-stderr-to-variable-in-powershell
if ( $null -ne $QueryOutput.Exception ) {
if ( "$($QueryOutput.Exception)" -like "*Error: database is locked" ) {
Write-Host "Database is locked, taking a break"
Start-Sleep -Seconds 1
Send-Query "$Query"
} else {
Write-Host "Send-Query encountered an error"
Write-Host $QueryOutput.Exception
}
}
$QueryOutput
}
$ComputerId = Send-Query "SELECT ComputerId FROM Computers WHERE Name LIKE '$Name';"
if ( $null -eq $ComputerId ) {
Write-Error "Unable to find computer '$Name' in database"
Exit 20
}
Write-Output "ComputerId: $ComputerId"
$Tables = @("Agents", "AgentEvents", "AgentInboundMessageLog", "AgentPublicKeys", "AgentPublicKeys_Backup")
ForEach ( $Table in $Tables ) {
$TableExists = Send-Query ".tables" | Where-Object { $_ -match "$Table" }
if ( $null -eq $TableExists ) {
Write-Verbose "Table $Table does not exist"
continue
}
$Count = Send-Query "SELECT COUNT(*) FROM $Table WHERE ComputerId = $ComputerId;"
Write-Output "$Count records in $Table"
Send-Query "DELETE FROM $Table WHERE ComputerId = $ComputerId;"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.