🐍 Python 3.10+

Backup Printers to JSON (Python)

Snapshots Printers (Win32_Printer) to a timestamped JSON file for later comparison or auditing.

By WindowsScripting.com · 1.2 KB
backup_printer_to_json.py
#!/usr/bin/env python3
"""
backup_printer_to_json.py

Snapshots Printers (Win32_Printer) to a timestamped JSON file, useful for
comparing point-in-time state later. Stdlib only.

Usage:
    python backup_printer_to_json.py [output_folder]
"""

import csv
import io
import json
import subprocess
import sys
from datetime import datetime
from pathlib import Path


def main() -> None:
    out_folder = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(".")
    out_folder.mkdir(parents=True, exist_ok=True)

    result = subprocess.run(
        ["wmic", "path", "Win32_Printer", "get", "Name,DriverName,PortName,PrinterStatus", "/format:csv"],
        capture_output=True, text=True, check=False,
    )
    if result.returncode != 0:
        sys.exit(f"wmic failed: {result.stderr.strip()}")

    lines = [line for line in result.stdout.splitlines() if line.strip()]
    rows = list(csv.DictReader(io.StringIO("\n".join(lines)))) if len(lines) >= 2 else []

    timestamp = datetime.now().strftime("%Y%m%d-%H%M%S")
    out_path = out_folder / f"printer-snapshot_{timestamp}.json"
    out_path.write_text(json.dumps(rows, indent=2), encoding="utf-8")

    print(f"Snapshot of Printers ({len(rows)} items) saved to {out_path}")


if __name__ == "__main__":
    main()