Catching the Exact Moment a File Arrives in a Folder — Change Monitoring with PowerShell + FileSystemWatcher

PowerShellカテゴリを表すパンダのイラスト PowerShell

About This Article
This article was created using an automated generation workflow leveraging generative AI. It reviews the .NET FileSystemWatcher specifications and is organized as a tip for monitoring folder changes using events in PowerShell.

Verification Status: 📘 Official API Verified · PowerShell Sample Implemented · Physical Device Unverified

Catching the Exact Moment a File Arrives in a Folder — Change Monitoring with PowerShell + FileSystemWatcher

“I want to process a CSV as soon as it is placed in a shared folder.” While you could periodically repeat Get-ChildItem, .NET provides FileSystemWatcher specifically designed to receive file system change notifications.

You can call it directly from PowerShell.

Short and Simple for Created Events Only

# FileSystemWatcher is a .NET class that monitors folder changes.


# Target only *.txt in C:Temp.

$watcher = [System.IO.FileSystemWatcher]::new("C:Temp", "*.txt")

# Register the action to execute when a Created event occurs.

Register-ObjectEvent $watcher Created -Action {

    # SourceEventArgs.FullPath contains the full path of the created file.

    Write-Host "Created:" $Event.SourceEventArgs.FullPath
}

# Start actual event notifications here.

$watcher.EnableRaisingEvents = $true

# FileSystemWatcher is event-driven.


# This while loop does not search for files every second; it acts as a wait to keep the script from terminating.

while ($true) { Start-Sleep 1 }

With just this, event processing runs whenever a txt file is created in the target folder.

All Four Events in the Complete Version

The GitHub version registers Created / Changed / Deleted / Renamed events, and cleans up the event registrations and FileSystemWatcher upon exit.

sequenceDiagram
    participant OS as File system
    participant F as FileSystemWatcher
    participant PS as PowerShell
    OS-->>F: 変更通知
    F-->>PS: Event
    PS->>PS: ログ・後続処理

“Monitoring” vs. “Auditing”

When a large number of changes occur in a short period of time, you need to account for potential duplicate notifications and internal buffer issues. It is safer not to rely on this alone as the authoritative audit log where zero dropouts are acceptable.

On the other hand, it is extremely convenient for supplementary automation and working folder monitoring.

GitHub Sample

Official & Primary Information

ライセンス:本記事のテキスト/コードは特記なき限り CC BY 4.0 です。引用の際は出典URL(本ページ)を明記してください。
利用ポリシー もご参照ください。

コメント

Copied title and URL