This article describes using PowerShell to monitor a specified folder, including creating new files, deleting files, renaming files, and so on, that are monitored or monitored. This article uses System.IO.FileSystemWatcher this. NET object. First, let's take a look at the program:
Copy Code code as follows:
# define the folders you want to monitor, this folder must first exist.
$folder = ' D:\test '
# defines the interval of each monitoring time, defined as 1000 milliseconds, or 1 seconds.
$timeout = 1000
# Create File System monitoring objects
$FileSystemWatcher = New-object System.IO.FileSystemWatcher $folder
Write-host "Press CTRL + C to exit monitoring of the folder $folder"
while ($true) {
# Monitor all changes in the folder
$result = $FileSystemWatcher. WaitForChanged (' All ', $timeout)
if ($result. Timedout-eq $false)
{
# Alert when contents of folder change
Write-warning (' File {0}: {1} '-F $result. ChangeType, $result. Name)
}
}
Write-host ' monitoring was canceled. '
Description: This program will monitor folder $folder, this folder must first exist. Then execute this PowerShell script. When you operate on this folder, such as creating a new file, renaming the file, deleting a file, and so on, the command line window where the PowerShell program is located will be prompted. Small series of tests when the prompts are as follows:
Copy Code code as follows:
Ps> D:\POWERSHELL\FS-MONITOR.PS1
Press CTRL + C to exit monitoring of the folder D:\test
Warning: File Created: New text file. txt
Warning: File Renamed:test.txt
Warning: File Deleted:test.txt
The creation, renaming, deletion, and so on of subfolders are also recorded, and even files are created in subfolders, and programs can be monitored.