PowerShell Script Monitor folder change instance _powershell

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.