如何检测文件夹中是否添加了任何文件?

时间:2014-05-20 17:41:12

标签: windows powershell windows-server

是否可以检测文件夹中是否添加了任何文件?包括子文件夹。

例如,检查文件夹*.txt或其子文件夹中是否添加了任何文本文件c:\data-files\

该文件夹也可以是其他机器的共享文件夹。

1 个答案:

答案 0 :(得分:1)

也许您对触发的事件类型感到困惑: http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher_events(v=vs.110).aspx

这应该起作用,取自上面的链接并根据您的要求进行修改:

#By BigTeddy 05 September 2011 

#This script uses the .NET FileSystemWatcher class to monitor file events in folder(s). 
#The advantage of this method over using WMI eventing is that this can monitor sub-folders. 
#The -Action parameter can contain any valid Powershell commands.  I have just included two for example. 
#The script can be set to a wildcard filter, and IncludeSubdirectories can be changed to $true. 
#You need not subscribe to all three types of event.  All three are shown for example. 
# Version 1.1 

$folder = '\\remote\shared' # Enter the root path you want to monitor. 
$filter = '*.txt'  # You can enter a wildcard filter here. 

# In the following line, you can change 'IncludeSubdirectories to $true if required.                           
$fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{IncludeSubdirectories = $true;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'} 

# Here, all three events are registerd.  You need only subscribe to events that you need: 

Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action { 
$name = $Event.SourceEventArgs.Name 
$changeType = $Event.SourceEventArgs.ChangeType 
$timeStamp = $Event.TimeGenerated 
Write-Host "The file '$name' was $changeType at $timeStamp" -fore green 
Out-File -FilePath c:\scripts\filechange\outlog.txt -Append -InputObject "The file '$name' was $changeType at $timeStamp"} 

请注意,关闭powershell控制台后,fileSystemWatcher将被丢弃,并且将不再监视文件夹。所以你必须确保powershell窗口保持打开状态。为了做到这一点,如果没有它妨碍你我建议一个预定的任务http://blogs.technet.com/b/heyscriptingguy/archive/2011/01/12/use-scheduled-tasks-to-run-powershell-commands-on-windows.aspx