This PowerShell script monitors a specific folder on the computer...

August 28, 2025 at 05:15 PM

# =========================== # Watch-PDFs-for-Digital-Signature.ps1 # =========================== $WatchFolder = "$env:"Users\Desktop\Documents for Digital Signature"" # folder to watch $pDocPath = ""C:\Program Files (x86)\pDoc Signer\pDoc Signer.exe"" # path to pDoc app # log file for basic diagnostics $LogFile = "$env:LOCALAPPDATA\pDocWatcher\pDocWatcher.log" New-Item -ItemType Directory -Path (Split-Path $LogFile) -Force | Out-Null function Write-Log { param([string]$Message) $stamp = (Get-Date).ToString("yyyy-MM-dd HH:mm:ss") "$stamp $Message" | Out-File -FilePath $LogFile -Append -Encoding utf8 } # Wait until file copy is complete and the file is unlocked function Wait-ForFileReady { param([string]$Path, [int]$TimeoutSec = 60) $sw = [Diagnostics.Stopwatch]::StartNew() $lastSize = -1 while ($sw.Elapsed.TotalSeconds -lt $TimeoutSec) { try { if (-not (Test-Path -LiteralPath $Path)) { Start-Sleep -Milliseconds 200; continue } $info = Get-Item -LiteralPath $Path -ErrorAction Stop # If size is stable for 1 second and file can be opened for Read, consider it ready if ($info.Length -eq $lastSize -and $lastSize -ge 0) { $fs = [System.IO.File]::Open($Path, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::Read) $fs.Close() return $true } $lastSize = $info.Length } catch { } Start-Sleep -Seconds 1 } return $false } # Debounce table to avoid double-firing on Created + Changed $recent = New-Object System.Collections.Concurrent.ConcurrentDictionary[string, datetime] # Event handler $onEvent = Register-ObjectEvent -InputObject (New-Object IO.FileSystemWatcher $WatchFolder, "*.pdf") ` -EventName Created ` -Action { param($sender, $eventArgs) $path = $eventArgs.FullPath $name = $eventArgs.Name # Debounce: ignore if fired within last 5 seconds for same file $now = Get-Date $last = $using:recent.GetOrAdd($path, [datetime]::MinValue) if (($now - $last).TotalSeconds -lt 5) { return } $using:recent[$path] = $now # Wait for file to be ready if (-not (Wait-ForFileReady -Path $path -TimeoutSec 120)) { Write-Log "Timeout waiting for file to be ready: $name" return } # Launch pDoc with the file try { if (-not (Test-Path -LiteralPath $using:pDocPath)) { Write-Log "pDoc path not found: $using:pDocPath" return } Write-Log "Opening in pDoc: $name" Start-Process -FilePath $using:pDocPath -ArgumentList "`"$path`"" } catch { Write-Log "Error launching pDoc for $name : $($_.Exception.Message)" } } # Also watch for files dropped via copy where Changed fires but Created was missed $onEvent2 = Register-ObjectEvent -InputObject (New-Object IO.FileSystemWatcher $WatchFolder, "*.pdf") ` -EventName Changed ` -Action { param($sender, $eventArgs) $path = $eventArgs.FullPath if (-not (Test-Path -LiteralPath $path)) { return } # Re-use same debounce logic $now = Get-Date $last = $using:recent.GetOrAdd($path, [datetime]::MinValue) if (($now - $last).TotalSeconds -lt 5) { return } $using:recent[$path] = $now if (-not (Wait-ForFileReady -Path $path -TimeoutSec 120)) { return } try { if (-not (Test-Path -LiteralPath $using:pDocPath)) { return } Write-Log "Opening in pDoc (Changed): $(Split-Path $path -Leaf)" Start-Process -FilePath $using:pDocPath -ArgumentList "`"$path`"" } catch { } } Write-Log "Watching folder: $WatchFolder" Write-Host "Watching $WatchFolder for PDFs. Press Ctrl+C to stop." while ($true) { Start-Sleep -Seconds 30 }

This PowerShell script monitors a specific folder on the computer for newly created or changed PDF files and automatically opens them in the pDoc Signer application for processing. Here's a break-down of what it specifically does:

  1. Set Up Folder and Paths:

    • The $WatchFolder variable defines the directory (on the Desktop, under Documents for Digital Signature) to monitor for PDF files.
    • $pDocPath points to the location of the pDoc Signer application on the system (assumed to be located at C:\Program Files (x86)\pDoc Signer\pDoc Signer.exe).
    • A log file path ($LogFile) is set up for diagnostic purposes in the user's local application data directory.
  2. Logging Functionality:

    • The Write-Log function records timestamped messages to the log file for debugging or tracking events.
  3. File Readiness Checker (Wait-ForFileReady):

    • This function ensures that the file is fully written to disk and is no longer locked by other processes (e.g., the copying or saving process has completed).
    • It periodically checks the file size and attempts to open the file for reading. If it detects stability (size does not change and the file can be opened) within a timeout period (default 60 seconds), it considers the file ready.
  4. Debounce Mechanism:

    • A ConcurrentDictionary object ($recent) is used to avoid processing the same file multiple times (e.g., handling both "Created" and "Changed" events or duplicate events within 5 seconds).
  5. Event Handlers for Watching Files:

    • Two event handlers ($onEvent and $onEvent2) are created with the FileSystemWatcher object to monitor the folder for PDF files (*.pdf) and react to file system events:
      • Created Event: Triggered when a new PDF file is created in the folder. It:
        • Checks if the event was recently handled (debounce logic).
        • Uses the Wait-ForFileReady function to ensure the file is ready.
        • Launches the pDoc Signer application with the PDF file as an argument.
      • Changed Event: Triggered when an existing PDF file is modified. It uses the same logic as the "Created" handler to process such files (useful for cases where the "Created" event is missed).
  6. Continuous Monitoring:

    • The script enters an infinite loop (while ($true) { Start-Sleep -Seconds 30 }) to keep monitoring the folder indefinitely until the user manually stops the script (e.g., using Ctrl+C).
  7. Error Handling:

    • The script includes error handling in key places (e.g., when trying to launch pDoc Signer or waiting for the file to be ready) and logs any issues it encounters.

High-Level Summary

This script automates the process of opening newly created or modified PDF files from a specific folder (Documents for Digital Signature) in the pDoc Signer application. It ensures files are fully ready before processing, avoids redundant processing of the same files, and logs all significant actions for debugging or diagnostics.

Generate your own explanations
Download our vscode extension
Read other generated explanations

Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node