Created
October 18, 2018 17:22
-
-
Save Colby-PDQ/d3b1d46473f6d26655b79f0e84527fb2 to your computer and use it in GitHub Desktop.
Removes Agent records from your Inventory Server's database.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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