Skip to content

Instantly share code, notes, and snippets.

@aidansteele
Last active July 11, 2026 11:40
Show Gist options
  • Select an option

  • Save aidansteele/ee760cabb795fdffd70db98b68313589 to your computer and use it in GitHub Desktop.

Select an option

Save aidansteele/ee760cabb795fdffd70db98b68313589 to your computer and use it in GitHub Desktop.
collect.ps1
param(
[string]$OutputDirectory = (Join-Path ([Environment]::GetFolderPath('Desktop')) ("iVMS4200-Collection-{0}" -f (Get-Date -Format 'yyyyMMdd-HHmmss'))),
[switch]$IncludeDpapi,
[switch]$NoArchive
)
$ErrorActionPreference = 'Stop'
Set-StrictMode -Version 2
if ($env:OS -ne 'Windows_NT') {
throw 'This script must be run on Windows.'
}
function Write-Status {
param([string]$Message)
Write-Host ("[{0}] {1}" -f (Get-Date -Format 'HH:mm:ss'), $Message)
}
function Get-CollectionDestination {
param(
[Parameter(Mandatory = $true)] [string]$Source,
[Parameter(Mandatory = $true)] [string]$CollectionRoot
)
$fullPath = [IO.Path]::GetFullPath($Source).TrimEnd('\')
$pathRoot = [IO.Path]::GetPathRoot($fullPath)
$driveName = $pathRoot.TrimEnd('\').TrimEnd(':')
$relativePath = $fullPath.Substring($pathRoot.Length).TrimStart('\')
return Join-Path (Join-Path $CollectionRoot 'Files') (Join-Path $driveName $relativePath)
}
function Copy-CollectionDirectory {
param(
[Parameter(Mandatory = $true)] [string]$Source,
[Parameter(Mandatory = $true)] [string]$CollectionRoot,
[Parameter(Mandatory = $true)] [string]$LogPath
)
if (-not (Test-Path -LiteralPath $Source -PathType Container)) {
return
}
$destination = Get-CollectionDestination -Source $Source -CollectionRoot $CollectionRoot
New-Item -ItemType Directory -Force -Path $destination | Out-Null
Write-Status "Copying $Source"
$robocopyOutput = & robocopy.exe $Source $destination /E /COPY:DAT /DCOPY:DAT /R:1 /W:1 /XJ /SL /NP 2>&1
$robocopyExitCode = $LASTEXITCODE
$robocopyOutput | Out-File -LiteralPath $LogPath -Append -Encoding utf8
if ($robocopyExitCode -ge 8) {
"WARNING: robocopy returned exit code $robocopyExitCode for $Source" |
Out-File -LiteralPath $LogPath -Append -Encoding utf8
Write-Warning "Some files could not be copied from $Source (robocopy exit code $robocopyExitCode)."
}
}
function Export-RegistryKeyIfPresent {
param(
[Parameter(Mandatory = $true)] [string]$Key,
[Parameter(Mandatory = $true)] [string]$Destination,
[Parameter(Mandatory = $true)] [string]$LogPath
)
# Windows PowerShell turns reg.exe's normal "key not found" stderr into an
# ErrorRecord. Temporarily suppress it so absent optional keys are skipped.
$previousErrorActionPreference = $ErrorActionPreference
$queryExitCode = 1
try {
$ErrorActionPreference = 'SilentlyContinue'
& reg.exe query $Key 1>$null 2>$null
$queryExitCode = $LASTEXITCODE
}
finally {
$ErrorActionPreference = $previousErrorActionPreference
}
if ($queryExitCode -ne 0) {
return
}
Write-Status "Exporting registry key $Key"
$output = @()
$exportExitCode = 1
try {
$ErrorActionPreference = 'Continue'
$output = & reg.exe export $Key $Destination /y 2>&1
$exportExitCode = $LASTEXITCODE
}
finally {
$ErrorActionPreference = $previousErrorActionPreference
}
$output | Out-File -LiteralPath $LogPath -Append -Encoding utf8
if ($exportExitCode -ne 0) {
Write-Warning "Could not export $Key. Try running PowerShell as Administrator."
}
}
$collectionRoot = [IO.Path]::GetFullPath($OutputDirectory)
if (Test-Path -LiteralPath $collectionRoot) {
throw "The output directory already exists: $collectionRoot"
}
New-Item -ItemType Directory -Force -Path $collectionRoot | Out-Null
$metadataDirectory = New-Item -ItemType Directory -Force -Path (Join-Path $collectionRoot 'Metadata')
$registryDirectory = New-Item -ItemType Directory -Force -Path (Join-Path $collectionRoot 'Registry')
$copyLog = Join-Path $metadataDirectory 'copy.log'
@"
iVMS-4200 collection created: $(Get-Date -Format o)
Computer: $env:COMPUTERNAME
Windows user: $env:USERDOMAIN\$env:USERNAME
DPAPI material included: $IncludeDpapi
This collection may contain access-control records, names, device credentials, and other secrets.
Store and transfer it securely.
"@ | Set-Content -LiteralPath (Join-Path $metadataDirectory 'collection-info.txt') -Encoding utf8
$relatedProcesses = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | Where-Object {
$_.Name -match '(?i)(ivms|hikvision)' -or $_.ExecutablePath -match '(?i)(ivms|hikvision)'
}
if ($relatedProcesses) {
$relatedProcesses |
Select-Object Name, ProcessId, ExecutablePath, CommandLine |
Export-Csv -LiteralPath (Join-Path $metadataDirectory 'running-hikvision-processes.csv') -NoTypeInformation -Encoding utf8
Write-Warning 'Hikvision/iVMS processes are running. Open database files may change during collection.'
Write-Warning 'For the most consistent copy, close iVMS (including its tray icon) before continuing.'
$answer = Read-Host 'Type CONTINUE to collect anyway, or press Enter to stop'
if ($answer -cne 'CONTINUE') {
Remove-Item -LiteralPath $collectionRoot -Recurse -Force
throw 'Collection cancelled. Close iVMS and run the script again.'
}
}
$candidateDirectories = New-Object System.Collections.Generic.List[string]
foreach ($path in @(
(Join-Path $env:ProgramData 'Hikvision'),
(Join-Path $env:ProgramData 'iVMS-4200'),
(Join-Path $env:ProgramData 'iVMS-4200 Site'),
(Join-Path $env:ProgramData 'iVMS-4200 AC'),
(Join-Path $env:APPDATA 'Hikvision'),
(Join-Path $env:APPDATA 'iVMS-4200'),
(Join-Path $env:LOCALAPPDATA 'Hikvision'),
(Join-Path $env:LOCALAPPDATA 'iVMS-4200'),
(Join-Path ([Environment]::GetFolderPath('MyDocuments')) 'iVMS-4200'),
(Join-Path $env:PUBLIC 'Documents\iVMS-4200')
)) {
if ($path -and -not $candidateDirectories.Contains($path)) {
$candidateDirectories.Add($path)
}
}
# iVMS-4200 3.7 can keep writable databases and logs inside its installation tree.
# Copy the complete product directory so extensionless and version-specific files are retained.
foreach ($programFilesRoot in @($env:ProgramFiles, ${env:ProgramFiles(x86)})) {
if (-not $programFilesRoot) {
continue
}
foreach ($relativePath in @(
'Hikvision',
'iVMS-4200',
'iVMS-4200 Site',
'iVMS-4200 AC'
)) {
$path = Join-Path $programFilesRoot $relativePath
if (-not $candidateDirectories.Contains($path)) {
$candidateDirectories.Add($path)
}
}
}
# Include matching data directories belonging to other Windows profiles. Access failures are
# recorded but do not abort collection.
$usersRoot = Join-Path $env:SystemDrive 'Users'
if (Test-Path -LiteralPath $usersRoot) {
foreach ($profile in Get-ChildItem -LiteralPath $usersRoot -Directory -Force -ErrorAction SilentlyContinue) {
foreach ($relativePath in @(
'AppData\Roaming\Hikvision',
'AppData\Roaming\iVMS-4200',
'AppData\Local\Hikvision',
'AppData\Local\iVMS-4200',
'AppData\Local\VirtualStore\Program Files\Hikvision',
'AppData\Local\VirtualStore\Program Files\iVMS-4200 Site',
'AppData\Local\VirtualStore\Program Files (x86)\Hikvision',
'AppData\Local\VirtualStore\Program Files (x86)\iVMS-4200 Site',
'Documents\iVMS-4200'
)) {
$path = Join-Path $profile.FullName $relativePath
if (-not $candidateDirectories.Contains($path)) {
$candidateDirectories.Add($path)
}
}
}
}
foreach ($directory in $candidateDirectories) {
try {
Copy-CollectionDirectory -Source $directory -CollectionRoot $collectionRoot -LogPath $copyLog
}
catch {
"ERROR copying ${directory}: $($_.Exception.Message)" | Out-File -LiteralPath $copyLog -Append -Encoding utf8
Write-Warning "Could not copy $directory"
}
}
if ($IncludeDpapi) {
$protectDirectory = Join-Path $env:APPDATA 'Microsoft\Protect'
Copy-CollectionDirectory -Source $protectDirectory -CollectionRoot $collectionRoot -LogPath $copyLog
}
$registryKeys = @(
@{ Key = 'HKCU\Software\Hikvision'; File = 'HKCU-Software-Hikvision.reg' },
@{ Key = 'HKCU\Software\iVMS-4200'; File = 'HKCU-Software-iVMS-4200.reg' },
@{ Key = 'HKLM\SOFTWARE\Hikvision'; File = 'HKLM-Software-Hikvision.reg' },
@{ Key = 'HKLM\SOFTWARE\iVMS-4200'; File = 'HKLM-Software-iVMS-4200.reg' },
@{ Key = 'HKLM\SOFTWARE\WOW6432Node\Hikvision'; File = 'HKLM-WOW6432Node-Hikvision.reg' },
@{ Key = 'HKLM\SOFTWARE\WOW6432Node\iVMS-4200'; File = 'HKLM-WOW6432Node-iVMS-4200.reg' }
)
foreach ($entry in $registryKeys) {
Export-RegistryKeyIfPresent `
-Key $entry.Key `
-Destination (Join-Path $registryDirectory $entry.File) `
-LogPath $copyLog
}
$uninstallRoots = @(
'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*',
'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*',
'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*'
)
Get-ItemProperty $uninstallRoots -ErrorAction SilentlyContinue |
Where-Object {
$displayNameProperty = $_.PSObject.Properties['DisplayName']
$displayNameProperty -and $displayNameProperty.Value -match '(?i)(ivms|hikvision)'
} |
Select-Object DisplayName, DisplayVersion, Publisher, InstallDate, InstallLocation, UninstallString |
Export-Csv -LiteralPath (Join-Path $metadataDirectory 'installed-products.csv') -NoTypeInformation -Encoding utf8
$installationDirectories = foreach ($programFilesRoot in @($env:ProgramFiles, ${env:ProgramFiles(x86)})) {
if (-not $programFilesRoot) {
continue
}
foreach ($directoryName in @('Hikvision', 'iVMS-4200', 'iVMS-4200 Site', 'iVMS-4200 AC')) {
$path = Join-Path $programFilesRoot $directoryName
if (Test-Path -LiteralPath $path -PathType Container) {
$path
}
}
}
$installationDirectories = $installationDirectories | Select-Object -Unique
$installationInventory = foreach ($directory in $installationDirectories) {
Get-ChildItem -LiteralPath $directory -File -Recurse -Force -ErrorAction SilentlyContinue | ForEach-Object {
[PSCustomObject]@{
Path = $_.FullName
Length = $_.Length
LastWriteTimeUtc = $_.LastWriteTimeUtc.ToString('o')
FileVersion = $_.VersionInfo.FileVersion
ProductVersion = $_.VersionInfo.ProductVersion
}
}
}
$installationInventory |
Export-Csv -LiteralPath (Join-Path $metadataDirectory 'installation-files.csv') -NoTypeInformation -Encoding utf8
Get-CimInstance Win32_OperatingSystem |
Select-Object Caption, Version, BuildNumber, OSArchitecture, InstallDate, LastBootUpTime |
Format-List |
Out-File -LiteralPath (Join-Path $metadataDirectory 'windows-version.txt') -Encoding utf8
Write-Status 'Generating SHA-256 manifest'
$manifestPath = Join-Path $metadataDirectory 'sha256.csv'
Get-ChildItem -LiteralPath $collectionRoot -File -Recurse -Force |
Where-Object { $_.FullName -ne $manifestPath } |
ForEach-Object {
$hash = Get-FileHash -LiteralPath $_.FullName -Algorithm SHA256
[PSCustomObject]@{
RelativePath = $_.FullName.Substring($collectionRoot.Length).TrimStart('\')
Length = $_.Length
SHA256 = $hash.Hash
}
} |
Export-Csv -LiteralPath $manifestPath -NoTypeInformation -Encoding utf8
if (-not $NoArchive) {
$archivePath = "$collectionRoot.zip"
Write-Status "Creating archive $archivePath"
if (Get-Command tar.exe -ErrorAction SilentlyContinue) {
& tar.exe -a -c -f $archivePath -C $collectionRoot .
if ($LASTEXITCODE -ne 0) {
throw "tar.exe failed to create $archivePath"
}
}
else {
Compress-Archive -Path (Join-Path $collectionRoot '*') -DestinationPath $archivePath -CompressionLevel Optimal
}
Write-Status "Done. Archive: $archivePath"
}
else {
Write-Status "Done. Collection: $collectionRoot"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment