首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何检测文件夹中是否添加了任何文件?

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

Stack Overflow用户
提问于 2014-05-20 17:41:12
回答 1查看 2.5K关注 0票数 1

这是一种检测文件夹中是否添加了任何文件的方法?包括子文件夹。

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

该文件夹也可以是另一台计算机的共享文件夹。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-05-20 19:16:33

也许您对触发的事件类型感到困惑:events(v=vs.110).aspx

这应该是可行的,从上面的链接中摘取,并根据您的需求进行修改:

代码语言:javascript
复制
#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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23766512

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档